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

Fab*_*ano 27 .net c# 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();
Run Code Online (Sandbox Code Playgroud)

这只会打印"Bar",因为"Foo"属于基类和私有.

Mar*_*ell 47

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

PropertyInfo[] props = someType.BaseType.GetProperties(
        BindingFlags.NonPublic | BindingFlags.Public
        | BindingFlags.Instance | BindingFlags.Static)
Run Code Online (Sandbox Code Playgroud)

  • 此外,可以遍历基类型(type = type.BaseType),直到type.BaseType为null,以获得完整的图片. (6认同)
  • @Fabiano你需要从s.GetType().BaseType调用GetProperties(),而不仅仅是GetType(). (5认同)
  • 遗憾的是,这不适用于基类的私有属性.仅适用于继承的公共和受保护的 (3认同)
  • 好吧,所以看起来你不能立刻获得所有属性,但必须手动检查所有基本类型.但是这样做会.谢谢 (2认同)

use*_*960 5

迭代基本类型 (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[] {});
Run Code Online (Sandbox Code Playgroud)