▲△▲△ 这是.NET Framework的bug吗?AttributeUsage的Inherited属性对Property无效!
MSDN 对 AttributeUsage 特性 Inherited 属性的说明:获取或设置一个布尔值,该值指示指示的属性能否由派生类和重写成员继承。
但是,请看以下试验 ——
//定义Attribute,将AttributeUsage的Inherited属性设为 true
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
public class MyAttribute : Attribute {}
public class MyClassBase
{
[MyAttribute] //将 Attribute 应用于方法上
public virtual void Method(){}
[MyAttribute] //将 Attribute 应用于属性上
public virtual int Property
{
get{return 0;}
set{}
}
}
public class MyClass: MyClassBase
{
public override void Method(){} //在派生类中重写方法
public override int Property //在派生类中重写属性
{
get{return 0;}
set{}
}
}
public class TestClass
{
public void run()
{
MyClass test = new MyClass();
//取应用于Method方法的特性个数
int a = test.GetType().GetMethod("Method").GetCustomAttributes(true).Length;
//取应用于Property属性的特性个数
int b = test.GetType().GetProperty("Property").GetCustomAttributes(true).Length;
// 输出结果
// a = 1 说明方法能成功继承父类的特性
// b = 0 说明属性无法继承父类的特性
// way ????
}
}
难道AttributeUsage的Inherited属性对Property无效吗?
那我要增加父类属性上的特性该怎么做??
忘高手们不吝赐教!!