获得基类的与反思私有属性/方法 [英] Get private Properties/Method of base-class with reflection

查看:126
本文介绍了获得基类的与反思私有属性/方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Type.GetProperties()则可以检索当前类和对应的公共属性的所有属性基类。是它在某种程度上可能得到基类的私人属性吗?

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

这将只打印酒吧,因为富是在基类和私有的。

This will only print "Bar" because "Foo" is in the base-class and private.

推荐答案

要获取的所有属性(公共+私有/保护/内部,静态+实例)给定的键入SOMETYPE (也许使用的GetType()获得 SOMETYPE

To get all properties (public + private/protected/internal, static + instance) of a given Type someType (maybe using GetType() to get someType):

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

这篇关于获得基类的与反思私有属性/方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆