继承属性

6

属性代码

[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");
        }
    }
}

输出:没有属性

为什么会出现这种情况呢?毕竟,它必须是继承的。

2个回答

5
继承标志决定属性是否可以被继承。默认情况下,此值为false。但是,如果将继承标志设置为true,则其含义取决于AllowMultiple标志的值。如果将继承标志设置为true且AllowMultiple标志为false,则该属性将覆盖继承的属性。但是,如果将继承标志设置为true且AllowMultiple标志也设置为true,则属性会在成员上累积。
来源:http://aclacl.brinkster.net/InsideC/32ch09f.htm,请查看“指定继承属性规则”一章。
编辑:请查看Abstract Properties上自定义属性的继承第一个答案:
GetCustomAttributes()方法不会查看父声明。它只查看应用于指定成员的属性。

3
不,"inherited" 的默认值为 true。https://msdn.microsoft.com/zh-cn/library/system.attributeusageattribute.inherited(v=vs.110).aspx - 00jt

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接