避免未密封的属性
更新:2007 年 11 月
TypeName |
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;
}
}
}
}
相关规则
用 AttributeUsageAttribute 标记属性