指定属性继承规则
AttributeUsage的最后一个参数是继承标志,指出速航行是否可以被继承。如果设为true,它的意义取决于AllowMultiple属性的值。
继承 | AllowMultiple | 结果 |
True | False | 派生的属性覆盖基属性 |
True | True | 派生的属性和基属性共存 |
using
System;
using System.Reflection;
namespace AttribInheritance
{
[AttributeUsage(
AttributeTargets.All,
//AllowMultiple=true,
AllowMultiple=false,
Inherited=true
)]
public class SomethingAttribute : Attribute
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public SomethingAttribute(string str)
{
this.name = str;
}
}
[Something("abc")]
class MyClass
{
}
[Something("def")]
class Another : MyClass
{
}
class Test
{
[STAThread]
static void Main(string[] args)
{
Type type = Type.GetType("AttribInheritance.Another");
foreach(Attribute attr in
type.GetCustomAttributes(true))
//type.GetCustomAttributes(false))
{
SomethingAttribute sa = attr as SomethingAttribute;
if(null != sa)
{
Console.WriteLine("Custom Attribute : {0}", sa.Name);
}
}
}
}
}
using System.Reflection;
namespace AttribInheritance
{
[AttributeUsage(
AttributeTargets.All,
//AllowMultiple=true,
AllowMultiple=false,
Inherited=true
)]
public class SomethingAttribute : Attribute
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public SomethingAttribute(string str)
{
this.name = str;
}
}
[Something("abc")]
class MyClass
{
}
[Something("def")]
class Another : MyClass
{
}
class Test
{
[STAThread]
static void Main(string[] args)
{
Type type = Type.GetType("AttribInheritance.Another");
foreach(Attribute attr in
type.GetCustomAttributes(true))
//type.GetCustomAttributes(false))
{
SomethingAttribute sa = attr as SomethingAttribute;
if(null != sa)
{
Console.WriteLine("Custom Attribute : {0}", sa.Name);
}
}
}
}
}
当AllowMultiple被设置为false时,结果为:
Custom Attribute : def
当AllowMultiple被设置为true时,结果为:
Custom Attribute : def
Custom Attribute : abc
注意,如果将false传递给GetCustomAttributes,它不会搜索继承树,所以你只能得到派生的类属性。