Inherited Attributes

Attribute code

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

Base class

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

Main class

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

Conclusion: don't have attr

Explain why this is happening? In the end, he must inherit.

+5
source share
2 answers

The inherited flag determines whether the attribute can be inherited. The default value for this value is false. However, if the inherited flag is set to true, its value depends on the value of the AllowMultiple flag. If the inherited flag is set to true and the AllowMultiple flag is false, the attribute will override the inherited attribute. However, if the inherited flag is true and the AllowMultiple flag is also set to true, the attribute accumulates on the member.

from http://aclacl.brinkster.net/InsideC/32ch09f.htm " "

EDIT: check :

GetCustomAttributes(), . , .

+5

All Articles