使用反射获取基类的私有属性/方法 [英] Get private Properties/Method of base-class with reflection
本文介绍了使用反射获取基类的私有属性/方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Type.GetProperties()
,您可以检索当前类的所有属性和基类的public
属性.是否也可以获取基类的 private
属性?
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?
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"位于基类和私有中.
This will only print "Bar" because "Foo" is in the base-class and private.
推荐答案
要获取给定 Type someType
的所有属性(public/private/protected/internal/static/instance),您必须访问使用 someType.BaseType
的基类.
To get all properties (public/private/protected/internal/static/instance) of a given Type someType
, you must access the base class by using someType.BaseType
.
示例:
PropertyInfo[] props = someType.BaseType.GetProperties(
BindingFlags.NonPublic | BindingFlags.Public
| BindingFlags.Instance | BindingFlags.Static)
这篇关于使用反射获取基类的私有属性/方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文