Share via


CA1813:避免使用未密封的特性

类型名

AvoidUnsealedAttributes

CheckId

CA1813

类别

Microsoft.Performance

是否重大更改

原因

继承自 System.Attribute 的某公共类型不是抽象类型且未密封(在 Visual Basic 中为 NotInheritable)。

规则说明

.NET Framework 类库提供用于检索自定义特性的方法。 默认情况下,这些方法搜索特性继承层次结构;例如,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 标记特性

请参见

参考

特性使用指南