I've been trying to use an attribute of a property that has been declared in an interface.
Assume:
[AttributeUsage(AttributeTargets.Property, Inherited=true)]
class My1Attribute : Attribute
{
public int x { get; set; }
}
interface ITest
{
[My1]
int y { get; set; }
}
class Child : ITest
{
public Child() { }
public int y { get; set; }
}
Now, from what I read, GetCustomAttribute() with inheritance=true should return the inherited attribute, but it looks it doesn't work.
Attribute my = typeof(Child).GetProperty("y").GetCustomAttribute(typeof(My1Attribute), true); // my == null
Why doesn't it work? and how can I get the attribute?
Child
does not have any custom attributes,ITest
has them, so you will have to callGetCustomAttributes
on the members ofITest
.There is a difference between inheritance and implementation. Inheritance would be fine if
Child
was derived from some base class that had ay
property decorated withMy1Attribute
.In your case,
Child
implementsITest
andITest
is a different type, outside of the inheritance hierarchy.