views:

1025

answers:

2

So, if i have:

public class Sedan : Car 
{
    /// ...
}

public class Car : Vehicle, ITurn
{
    [MyCustomAttribute(1)]
    public int TurningRadius { get; set; }
}

public abstract class Vehicle : ITurn
{
    [MyCustomAttribute(2)]
    public int TurningRadius { get; set; }
}

public interface ITurn
{
    [MyCustomAttribute(3)]
    int TurningRadius { get; set; }
}

What magic can I use to do something like:

[Test]
public void Should_Use_Magic_To_Get_CustomAttributes_From_Ancestry()
{
    var property = typeof(Sedan).GetProperty("TurningRadius");

    var attributes = SomeMagic(property);

    Assert.AreEqual(attributes.Count, 3);
}


Both

property.GetCustomAttributes(true);

And

Attribute.GetCustomAttributes(property, true);

Only return 1 attribute. The instance is the one built with MyCustomAttribute(1). This doesn't seem to work as expected.

A: 
object[] SomeMagic (PropertyInfo property)
{
    return property.GetCustomAttributes(true);
}

UPDATE:

Since my above answer doesn't work why not to try something like this:

public void Should_Use_Magic_To_Get_CustomAttributes_From_Ancestry()
{

    Assert.AreEqual(checkAttributeCount (typeof (Sedan), "TurningRadious"), 3);
}


int checkAttributeCount (Type type, string propertyName)
{
        var attributesCount = 0;

        attributesCount += countAttributes (type, propertyName);
        while (type.BaseType != null)
        {
            type = type.BaseType;
            attributesCount += countAttributes (type, propertyName);
        }

        foreach (var i in type.GetInterfaces ())
            attributesCount += countAttributes (type, propertyName);
        return attributesCount;
}

int countAttributes (Type t, string propertyName)
{
    var property = t.GetProperty (propertyName);
    if (property == null)
        return 0;
    return (property.GetCustomAttributes (false).Length);
}
AlbertEin
In the provided example the assertion fails. It returns 1 attribute, not all 3.
TheDeeno
You're right, that's because it's really just one customattribute.
AlbertEin
If I change the instance of the attribute it seems to only return the one on car. So its not searching after Car. See updated question. Ty for the help though.
TheDeeno
Ok, updated the answer, hope it helps
AlbertEin
+1  A: 

this is a framework issue. Interface attributes are ignored by GetCustomAttributes. see the comment on this blog post http://hyperthink.net/blog/getcustomattributes-gotcha/#comment-65

Damien McGivern