Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Output: don't have attr

Explain why this is happening? After all, it must inherited.

like image 882
turbanoff Avatar asked Apr 27 '12 09:04

turbanoff


1 Answers

The inherited flag dictates whether the attribute can be inherited. The default for this value is false. However, if the inherited flag is set to true, its meaning 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 set to true and the AllowMultiple flag is also set to true, the attribute accumulates on the member.

from http://aclacl.brinkster.net/InsideC/32ch09f.htm Check the chapter Specifying Inheritance Attribute Rules

EDIT: check Inheritance of Custom Attributes on Abstract Properties The first answer:

It's the GetCustomAttributes() method that does not look at parent declarations. It only looks at attributes applied to the specified member.

like image 100
amaters Avatar answered Oct 06 '22 02:10

amaters