【问题标题】:Inherited attributes继承的属性
【发布时间】:2012-05-08 01:16:55
【问题描述】:

属性代码

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

基类

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

主类

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

解释为什么会这样?毕竟,它必须继承。

【问题讨论】:

    标签: c# .net inheritance attributes


    【解决方案1】:

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

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

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

    是GetCustomAttributes()方法不看parent 声明。它只查看应用于指定的属性 会员。

    【讨论】:

    【解决方案2】:

    PropertyInfo.GetCustomAttributes 中的继承标志对于属性和事件都会被忽略,如 https://msdn.microsoft.com/en-us/library/dwc6ew1d.aspx 所述。但是您可以使用 Attribute.GetCustomAttributes 重载之一来启用属性(或事件)的继承。

    这个问题在http://blog.seancarpenter.net/2012/12/15/getcustomattributes-and-overridden-properties/有更详细的讨论

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-03
      • 1970-01-01
      • 2012-08-15
      • 2010-10-05
      • 1970-01-01
      • 2015-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多