C#中Attribute的继承
在C#中Attribute是个非常有用的语法,本文不会介绍Attribute的使用方法,如果想了解Attribute的详细信息请查阅MSDN及网上相关文档。C#中的Attribute有两个地方是和继承相关的,一个地方是AttributeUsageAttribute类中的属性参数Inherited,另一个地方是Type反射中的GetCustomAttributes方法(包括Type.GetCustomAttributes、MemberInfo.GetCustomAttributes等反射方法)的inherit参数,这两个与继承相关的参数都是bool类型,但是代表的含义却不相同,我们来看看他们分别代表的是什么:
AttributeUsageAttribute类的Inherited属性参数
AttributeUsage中的属性参数Inherited指的是继承链中的子类和子类成员是否能继承在父类和父类成员上声明的Attribute。我们来看个例子,假如现在我们有两个类BaseClass和MyClass,其中MyClass继承于BaseClass,现在我们在BaseClass上声明一个自定义Attribute叫MyAttribute,代码如下:
[My] class BaseClass { } class MyClass:BaseClass { }
如果像下面代码中设置MyAttribute上AttributeUsage的属性参数Inherited为true,则代表MyAttribute是可以被继承声明的,也就是说上面代码中在父类BaseClass上声明了MyAttribute后,子类MyClass相当于也声明了MyAttribute。
[AttributeUsage(AttributeTargets.All, Inherited = true)] class MyAttribute : Attribute { }
如果像下面代码中设置MyAttribute上AttributeUsage的属性参数Inherited为false,那么代表MyAttribute是无法被继承声明的,也就是说上面代码中在父类BaseClass上声明了MyAttribute后,子类MyClass不具有MyAttribute,相当于父类BaseClass声明了MyAttribute但是子类MyClass没有声明MyAttribute。
[AttributeUsage(AttributeTargets.All, Inherited = false)] class MyAttribute : Attribute { }
GetCustomAttributes方法的inherit参数
GetCustomAttributes方法中inherit参数指的是当调用GetCustomAttributes方法的地方是在继承链中的父类时,GetCustomAttributes方法是否搜索子类和子类成员上声明或继承的Attribute。同样我们来看个例子,假如现在我们有两个类BaseClass和MyClass,其中MyClass继承于BaseClass,现在我们在BaseClass上声明一个自定义Attribute叫MyAttribute,代码如下:
[My] class BaseClass { } class MyClass:BaseClass { }
我们在MyAttribute上设置AttributeUsage的属性参数Inherited为true,那么相当于子类MyClass上也声明了MyAttribute:
[AttributeUsage(AttributeTargets.All, Inherited = true)] class MyAttribute : Attribute { }
现在如果我们调用构造函数构造一个MyClass对象,然后调用对象的反射方法GetCustomAttributes看是否能在MyClass上找到MyAttribute。如果找到了则在控制台输出找到了MyAttribute,否则输出没有找到。
首先我们调用GetCustomAttributes方法时将参数inherit设置为true。结果控制台显示:"MyAttribute found!",说明GetCustomAttributes方法成功找到了MyAttribute。
var my = new MyClass(); var myMyAttribute = my.GetType().GetCustomAttributes(typeof(MyAttribute), true); if (myMyAttribute != null && myMyAttribute.Count() > 0) { Console.WriteLine("MyAttribute found!"); } else { Console.WriteLine("MyAttribute not found!"); }
接着我们调用GetCustomAttributes方法时将参数inherit设置为false。这次控制台显示:"MyAttribute not found!",说明将参数inherit设置为false后GetCustomAttributes方法无法在MyClass上找到MyAttribute了。
var my = new MyClass(); var myMyAttribute = my.GetType().GetCustomAttributes(typeof(MyAttribute), false); if (myMyAttribute != null && myMyAttribute.Count() > 0) { Console.WriteLine("MyAttribute found!"); } else { Console.WriteLine("MyAttribute not found!"); }
原文:http://www.cnblogs.com/OpenCoder/p/5007472.html