CA1813:避免使用非密封屬性

型別名稱

AvoidUnsealedAttributes

CheckId

CA1813

分類

Microsoft.Performance

中斷變更

中斷

原因

繼承自 Attribute 的 public 型別既非抽象的,亦非密封的 (在 Visual Basic 中為 NotInheritable)。

規則描述

.NET Framework Class Library 會提供擷取自訂屬性的方法。根據預設,這些方法會搜尋屬性繼承階層架構 (Inheritance Hierarchy),例如 Attribute.GetCustomAttribute 會搜尋指定的屬性型別,或搜尋任何會擴充指定之屬性型別的屬性型別。密封屬性會減少對整個繼承階層架構的搜尋,並且可以改進效能。

如何修正違規

若要修正此規則的違規情形,請密封屬性型別或將它設為抽象。

隱藏警告的時機

您可以放心地隱藏這項規則的警告。但是您只能在定義屬性階層架構,卻無法密封屬性或將它設為抽象時,才能這麼做。

範例

在下列範例中,程式碼會顯示滿足此規則的自訂屬性。

Imports System

Namespace PerformanceLibrary

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

    Public Sub New(name As String)
        nameValue = name
    End Sub 


    Public ReadOnly Property Name() As String 
        Get 
            Return nameValue
        End Get 
    End Property 
End Class  

End Namespace
using System;

namespace PerformanceLibrary 
{
    // 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;
            }
        }
    }

}

相關規則

CA1019:必須定義屬性引數的存取子

CA1018:以 AttributeUsageAttribute 標記屬性

請參閱

其他資源

Attribute Usage Guidelines