C# 使用反射获取基类的私有属性/方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2267277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get private Properties/Method of base-class with reflection
提问by Fabiano
With Type.GetProperties()
you can retrieve all properties of your current class and the public
properties of the base-class. Is it somehow possible to get the private
properties of the base-class too?
有了Type.GetProperties()
你可以检索你的当前类的所有属性和public
基类的属性。是否也有可能获得private
基类的属性?
Thanks
谢谢
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();
This will only print "Bar" because "Foo" is in the base-class and private.
这只会打印“Bar”,因为“Foo”在基类和私有中。
采纳答案by Marc Gravell
To get all properties (public + private/protected/internal, static + instance) of a given Type someType
(maybe using GetType()
to get someType
):
要获取给定Type someType
(可能GetType()
用于 get someType
)的所有属性(公共 + 私有/受保护/内部、静态 + 实例):
PropertyInfo[] props = someType.BaseType.GetProperties(
BindingFlags.NonPublic | BindingFlags.Public
| BindingFlags.Instance | BindingFlags.Static)
回答by user1785960
Iterate through the base types (type = type.BaseType), until type.BaseType is null.
遍历基本类型 (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[] {});