2017-09-13 103 views
11

我有以下兩類(型號),一個是基類,另一個是子類:如何確定屬性是否屬於基類或子類動態使用反射的泛型類型?

public class BaseClass 
{  
    public string BaseProperty{get;set;}  
} 

public class ChildClass: BaseClass  
{  
    public string ChildProperty{get;set;}  
} 

在應用我打電話ChildClass動態使用泛型

List<string> propertyNames=new List<string>(); 
foreach (PropertyInfo info in typeof(T).GetProperties()) 
{ 
     propertyNames.Add(info.Name); 
} 

在這裏,propertyNames名單,我也獲得BaseClass的財產。我只想要那些在子類中的屬性。這可能嗎?

我試過了嗎?

  1. 嘗試過不包括它作爲在本question
  2. 試圖確定該類是否是子類或基類如所提here但這並沒有幫助提及。
+3

不錯q。我認爲你的意思是使用Reflection而不是泛型? – StuartLC

+1

https://stackoverflow.com/questions/12667219/reflection-exclude-all-attributes-from-base-class-and-specific-attribute-from-al – Ric

回答

9

你可以試試這個

foreach (PropertyInfo info in typeof(T).GetProperties() 
     .Where(x=>x.DeclaringType == typeof(T))) // filtering by declaring type 
{ 
    propertyNames.Add(info.Name); 
} 
+0

謝謝你的工作就像一個魅力:)你節省我的很多時間。 –

1

使用一個簡單的循環來獲得基類屬性名

var type = typeof(T); 

var nameOfBaseType = "Object"; 

while (type.BaseType.Name != nameOfBaseType) 
{ 
    type = type.BaseType; 
} 

propertyNames.AddRange(type.GetProperties().Select(x => x.Name)) 
+0

謝謝,但我不想要基類的屬性名稱。我只想要子類的屬性名稱。此外,一切都動態發生,所以我可能不會硬編碼並分配'nameofBaseType'變量。 –

1

...我只希望這是在子類中的那些屬性。這可能嗎?

您需要使用GetProperties重載需要一個BindingFlags參數,包括BindingFlags.DeclaredOnly標誌。

PropertyInfo[] infos = typeof(ChildClass).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); 

DeclaredOnly指定只成員在聲明所提供的類型的層次水平應予以考慮。不考慮繼承的成員。

+0

謝謝,但它不返回任何屬性。我錯過了什麼。你檢查這個[demo](http://rextester.com/MNAHMY33063)我使用你的代碼製作的。 –

+1

@KaranDesai,你需要包含我上面展示的三個BindingFlags。當你在不指定任何BindingFlags的情況下調用'GetProperties'時,它會使用'BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance'。所以你可能想要將'BindingFlags.Static'包含到列表中;它只是取決於你想要檢索的內容,並且是我提供了BindingFlags文檔鏈接的原因。 – TnTinMn

+0

謝謝澄清。 DeclaredOnly的描述讓我困惑。當我添加所有三個標誌時,這也起作用。 +1 –