2012-07-25 162 views
1

我在這裏簡單地提出了這個問題,因此該示例無法爲真實世界做出任何貢獻。無法通過反射獲取泛型類型的屬性

public class BusinessEntity<T> 
{ 
    public int Id {get; set;} 
} 

public class Customer : BusinessEntity<Customer> 
{ 

    public string FirstName { get; set;} 
    public string LastName { get; set;} 
} 

當我嘗試通過反射獲取Customer類屬性時,無法獲取泛型基類的屬性。如何從BusinessEntity獲取ID?

Type type = typeof(Customer); 

PropertyInfo[] properties = type.GetProperties(); 
// Just FirstName and LastName listed here. I also need Id here 
+1

剛剛測試過這種情況,我返回的屬性數組總是有3項(VS2012,嘗試多個目標框架)。 – Timbo 2012-07-25 07:58:56

+1

「如何從BusinessEntity獲取Id?」去洗你的眼睛? :p – 2012-07-25 08:00:25

+2

這裏有個訣竅:當你簡化問題的代碼時,*檢查它是否仍然顯示問題*。如果它沒有**顯示問題,那麼看看真實代碼和簡化代碼之間的區別,然後你自己回答*。 – 2012-07-25 08:03:10

回答

2

不,那肯定會返回所有3個屬性。請檢查您的實際代碼,Id是否爲internal/protected/etc(即非公開)。如果是,你需要在BindingFlags通過,例如:

PropertyInfo[] properties = type.GetProperties(
    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); 

(默認設置爲public +實例+靜態)

還要檢查它不是一個在實際代碼;如果是:

public int Id; 

那麼它是一個領域,你應該使用GetFields使Id屬性,P

+0

其實它已被宣佈爲領域,因爲你提到我的壞(:謝謝 – 2012-07-25 08:09:31

+0

+1,因爲我從你上面的評論中學到了一些新的東西回答 – HatSoft 2012-07-25 08:16:02

1

爲了讓你將不得不使用基本屬性該類型的BaseType屬性

PropertyInfo[] baseProperties = typeof(Customer).BaseType.GetProperties(BindingFlags.DeclaredOnly); 
PropertyInfo[] properties = typeof(Customer).GetProperties(); 
+1

@Ryu請參閱更新答案以獲取基類型屬性 – HatSoft 2012-07-25 08:02:32

+0

事情是......這不是真的,默認情況下你會得到繼承的屬性,事實上,你必須將額外的標誌傳遞給* not * get它們 – 2012-07-25 08:04:12

+0

@MarcGravell是的,我同意,但這是一種獲得類型基礎屬性的方法 – HatSoft 2012-07-25 08:05:40

1

什麼問題,您的代碼是完全正確的,並返回co rrect性能

Type type = typeof(Customer); 
PropertyInfo[] properties = type.GetProperties(); 
foreach(var prop in properties) 
{ Console.WriteLine(prop) } 

結果

System.String FirstName 
System.String LastName 
Int32 Id