2011-03-16 98 views
3

如何使用此方法獲取屬性類的值?變量類型參數

public static int SQLInsert<TEntity>(TEntity obj) where TEntity : class 
{ 
    foreach (var item in obj.GetType().GetProperties()) 
    { 
     //item.GetValue(?,null); 
    } 
    return 1; 
} 

回答

1
item.GetValue(obj, null); 

,將工作約TEntity喬恩

5

item將是一個PropertyInfo。你會用:

object value = item.GetValue(obj, null); 

請注意,你幾乎忽略了TEntity類型參數。您可能需要使用:

foreach (var property in typeof(TEntity).GetProperties()) 

這樣,如果有人呼叫

SQLInsert<Customer>(customer) 

customer實際上Customer具有額外屬性的子類的值,只有Customer屬性會用過的。

+0

+1非常好的問題,這些類型的細微之處都容易漏診。 – 2011-03-16 09:08:47

0

這樣,而不是索引,您可以使用空值:

public static int SQLInsert<TEntity>(TEntity obj) where TEntity : class 
{ 
    var indexer = new object[0]; 
    foreach (var item in obj.GetType().GetProperties()) 
    { 
     item.GetValue(obj,indexer); 
    } 
    return 1; 
}