CA1813:アンシールド属性を使用しません

プロパティ
ルール ID CA1813
Title アンシールド属性を使用しません
[カテゴリ] パフォーマンス
修正が中断ありか中断なしか あり
.NET 8 では既定で有効 いいえ

原因

パブリック型の継承元が System.Attribute であり、抽象型でなく、シールされていません (Visual Basic では NotInheritable)。

規則の説明

.NET には、カスタム属性を取得するメソッドが用意されています。 既定では、これらのメソッドで属性の継承階層が検索されます。 たとえば、System.Attribute.GetCustomAttribute では、指定された属性型、または指定された属性型を拡張するすべての属性型を検索します。 属性をシールすると、継承階層の全体が検索されなくなるため、パフォーマンスが向上します。

違反の修正方法

この規則の違反を修正するには、属性型をシールするか、抽象型にします。

どのようなときに警告を抑制するか

この規則による警告を抑制しても問題ありません。 属性階層を定義していて、属性をシールしたり抽象型にしたりできない場合のみ、抑制します。

警告を抑制する

単一の違反を抑制するだけの場合は、ソース ファイルにプリプロセッサ ディレクティブを追加して無効にしてから、規則をもう一度有効にします。

#pragma warning disable CA1813
// The code that's violating the rule is on this line.
#pragma warning restore CA1813

ファイル、フォルダー、またはプロジェクトの規則を無効にするには、構成ファイルでその重要度を none に設定します。

[*.{cs,vb}]
dotnet_diagnostic.CA1813.severity = none

詳細については、「コード分析の警告を抑制する方法」を参照してください。

次の例は、この規則を満たすカスタム属性を示しています。

// Satisfies rule: AvoidUnsealedAttributes.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public sealed class DeveloperAttribute : Attribute
{
    private string nameValue;
    public DeveloperAttribute(string name)
    {
        nameValue = name;
    }

    public string Name
    {
        get
        {
            return nameValue;
        }
    }
}
Imports System

Namespace ca1813

    ' Satisfies rule: AvoidUnsealedAttributes.
    <AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct)>
    Public NotInheritable Class DeveloperAttribute
        Inherits Attribute

        Public Sub New(name As String)
            Me.Name = name
        End Sub


        Public ReadOnly Property Name() As String
    End Class

End Namespace

関連項目