Mah*_*amy 0 c# virtual attributes
在MSDN 上,编写自定义属性的示例显示了以下奇怪的行为
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
public virtual string Name
{
get {return name;}
}
// Define Level property.
// This is a read-only attribute.
public virtual string Level
{
get {return level;}
}
// Define Reviewed property.
// This is a read/write attribute.
public virtual bool Reviewed
{
get {return reviewed;}
set {reviewed = value;}
}
}
Run Code Online (Sandbox Code Playgroud)
为什么所有的财产都是虚拟的?
OP 提到的特定 MSDN 文章中有一部分是关于属性“继承”的,即如果您有一个类的方法是虚拟的并用属性进行注释,并且您添加一个子类并覆盖该方法,子类方法是否应用了该属性?这[AttributeUsage(AttributeTargets.Method, Inherited = false)]就是继承属性部分的内容。
具体来说:
public class MyClass
{
[MyAttribute]
[YourAttribute]
public virtual void MyMethod()
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
其中 YourAttribute 配置为AttributeUsage(AttributeTargets.Method, Inherited = false)]MyAttribute 具有默认配置。
public class MyClass
{
[MyAttribute]
[YourAttribute]
public virtual void MyMethod()
{
//...
}
}
public class YourClass : MyClass
{
// MyMethod will have MyAttribute but not YourAttribute.
public override void MyMethod()
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
Inherited的默认值为true。
所以简而言之,这些属性在描述这个特性的文章中都是虚拟的。