属性でマークされたプロパティのインスタンス値を取得するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/208570

  •  03-07-2019
  •  | 
  •  

質問

次のように、カスタム属性でマークされたクラスがあります:

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