使用reflection获取基类的私有属性/方法

使用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(); 

这只会打印“Bar”,因为“Foo”属于基类和私有。

获取给定Type someType所有属性(public + private / protected / internal,static + instance)(可能使用GetType()获取someType ):

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

遍历基类型(type = type.BaseType),直到type.BaseType为null。

 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[] {});