2010-02-15 60 views
24

使用Type.GetProperties()您可以檢索當前類的所有屬性和基類的public屬性。是否有可能獲得基類的private屬性呢?獲取私有屬性/基礎類的反射方法

感謝

class Base 
{ 
    private string Foo { get; set; } 
} 

class Sub : Base 
{ 
    private string Bar { get; set; } 
} 


     Sub s = new Sub(); 
     PropertyInfo[] pinfos = s.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); 
     foreach (PropertyInfo p in pinfos) 
     { 
      Console.WriteLine(p.Name); 
     } 
     Console.ReadKey(); 

這將只打印「酒吧」,因爲「富」是在基類和私人。

回答

41

要獲得一個給定的Type someType(可能使用GetType()得到someType)的所有屬性(公共+私有/保護/內部,靜態+實例):通過基本類型

PropertyInfo[] props = someType.BaseType.GetProperties(
     BindingFlags.NonPublic | BindingFlags.Public 
     | BindingFlags.Instance | BindingFlags.Static) 
+6

此外,可以遍歷基類型(type = type.BaseType),直到type.BaseType爲null,以獲得完整的圖片。 – 2010-02-15 16:28:16

+3

不幸的是,這不適用於基類的私有屬性。只爲繼承公衆和保護 – Fabiano 2010-02-15 16:42:28

+0

@Fabiano - 非公共包括私人。 – 2010-02-15 16:56:37

2

迭代(type =類型.BaseType),直到type.BaseType爲空。

MethodInfo mI = null; 
Type baseType = someObject.GetType(); 
while (mI == null) 
{ 
    mI = baseType.GetMethod("SomePrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance); 
    baseType = baseType.BaseType; 
    if (baseType == null) break; 
} 
mI.Invoke(someObject, new object[] {});