2010-04-30 30 views
2

拿這個類,例如:C#與飾部件工作

public class Applicant : UniClass<Applicant> 
{ 
    [Key] 
    public int Id { get; set; } 

    [Field("X.838.APP.SSN")] 
    public string SSN { get; set; } 

    [Field("APP.SORT.LAST.NAME")] 
    public string FirstName { get; set; } 

    [Field("APP.SORT.FIRST.NAME")] 
    public string LastName { get; set; } 

    [Field("X.838.APP.MOST.RECENT.APPL")] 
    public int MostRecentApplicationId { get; set; } 
} 

我怎麼會去讓所有的裝飾與現場屬性的屬性,得到他們的類型,然後賦值給他們?

回答

2

你需要使用反射:

var props = 
    from prop in typeof(Applicant).GetProperties() 
    select new { 
     Property = prop, 
     Attrs = prop.GetCustomAttributes(typeof(FieldAttribute), false).Cast<FieldAttribute>() 
    } into propAndAttr 
    where propAndAttr.Attrs.Any() 
    select propAndAttr; 

然後,您可以通過此查詢重複設置的值:

foreach (var prop in props) { 
    var propType = prop.Property.PropertyType; 
    var valueToSet = GetAValueToSet(); // here's where you do whatever you need to do to determine the value that gets set 
    prop.Property.SetValue(applicantInstance, valueToSet, null); 
} 
4

這都是用反射完成的。一旦你有一個Type對象,你就可以從myType.GetProperties()那裏得到它的PropertyInfo,你可以從那裏得到每個屬性的屬性GetCustomAttributes(),如果你找到屬性,那麼你就有了一個贏家,然後你可以繼續隨你便宜。

你已經有PropertyInfo對象,這樣你就可以分配給它PropertyInfo.SetValue(object target, object value, object[] index)

1

你就只需要調用相應的反射方法 - 試試這個:

<MyApplicationInstance>.GetType().GetProperties().Where(x => x.GetCustomAttributes().Where(y => (y as FieldAttribute) != null).Count() > 0);