我有一个标有自定义属性的类,如下所示:

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

我想编写一个泛型方法,我需要在实体上获取属性,该属性标记为Parent属性。

这是我的属性:

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

我该怎么写?

有帮助吗?

解决方案

使用Type.GetProperties()和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;
    }

其他提示

这对我有用:

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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top