كيف يمكنني الحصول على قيمة مثيل خاصية تميز مع سمة؟

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

  •  03-07-2019
  •  | 
  •  

سؤال

ولدي الطبقة التي وضعت مع سمة مخصصة، مثل هذا:

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

وأريد أن أكتب طريقة عامة، حيث كنت بحاجة للحصول على الملكية على الكيان الذي يظهر على السمة الرئيسي.

وهنا هو بلدي السمة:

[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