views:

104

answers:

2

I have a class which is marked with a custom attribute, like this:

public class OrderLine : Entity
{
    ...
    [Parent]
    public Order Order { get; set; }
    public Address ShippingAddress{ get; set; }
    ...
}

I want to write a generic method, where I need to get the Property on a Entity which is marked with the Parent attribute.

Here is my Attribute:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class ParentAttribute : Attribute
{
}

How do I write this?

+2  A: 

This works for me:

public static object GetParentValue<T>(T obj) {
    Type t = obj.GetType();
    foreach (var prop in t.GetProperties()) {
        var attrs = prop.GetCustomAttributes(typeof(ParentAttribute), false);
        if (attrs.Length != 0)
            return prop.GetValue(obj, null);
    }

    return null;
}
Konrad Rudolph
+3  A: 

Use Type.GetProperties() and PropertyInfo.GetValue()

    T GetPropertyValue<T>(object o)
    {
        T value = default(T);

        foreach (System.Reflection.PropertyInfo prop in o.GetType().GetProperties())
        {
            object[] attrs = prop.GetCustomAttributes(typeof(ParentAttribute), false);
            if (attrs.Length > 0)
            {
                value = (T)prop.GetValue(o, null);
                break;
            }
        }

        return value;
    }
Jon B
I dont think that will compile. Look at the 'as T'.
leppie
You're right - fixed.
Jon B