2012-04-27 379 views
5

属性代码继承属性

[AttributeUsage(AttributeTargets.Property, Inherited = true)] 
class IgnoreAttribute : Attribute 
{ 
} 

基类

abstract class ManagementUnit 
{ 
    [Ignore] 
    public abstract byte UnitType { get; } 
} 

Main类

class Region : ManagementUnit 
{ 
    public override byte UnitType 
    { 
     get { return 0; } 
    } 

    private static void Main() 
    { 
     Type t = typeof(Region); 
     foreach (PropertyInfo p in t.GetProperties()) 
     { 
      if (p.GetCustomAttributes(typeof(IgnoreAttribute), true).Length != 0) 
       Console.WriteLine("have attr"); 
      else 
       Console.WriteLine("don't have attr"); 
     } 
    } 
} 

输出:don't have attr

解释为什么会发生这种情况?毕竟,它必须继承。

回答

5

继承标志指示属性是否可以继承。 此值的默认值为false。但是,如果继承标志 设置为true,则其含义取决于AllowMultiple 标志的值。如果继承标志设置为true,并且AllowMultiple标志 为false,则该属性将覆盖继承的属性。 但是,如果继承标志设置为true并且AllowMultiple 标志也设置为true,则该属性将在成员上累积。

http://aclacl.brinkster.net/InsideC/32ch09f.htm 检查章节指定继承属性规则

编辑:检查Inheritance of Custom Attributes on Abstract Properties 第一个答案:

这是GetCustomAttributes()方法,不看父母 声明。它仅查看应用于指定的 成员的属性。

+3

不,“继承”的默认值是true。 https://msdn.microsoft.com/en-us/library/system.attributeusageattribute.inherited(v=vs.110).aspx – 00jt 2015-08-13 18:08:50