C#:访问继承的私人实例成员通过反射 [英] C#: Accessing Inherited Private Instance Members Through Reflection

查看:90
本文介绍了C#:访问继承的私人实例成员通过反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#反射绝对新手。我想使用反射来访问所有的私人领域中的一类,包括那些继承。

I am an absolute novice at reflection in C#. I want to use reflection to access all of private fields in a class, including those which are inherited.

我已经成功地访问所有私有字段不包括那些被继承,以及公众和保护继承的字段所有。不过,我一直无法访问私有继承的字段。下面的例子说明:

I have succeeded in accessing all private fields excluding those which are inherited, as well as all of the public and protected inherited fields. However, I have not been able to access the private, inherited fields. The following example illustrates:

class A
{
    private string a;
    public string c;
    protected string d;
}

class B : A
{
    private string b;
}

class test
{
    public static void Main(string[] Args)
    {
        B b = new B();       
        Type t;
        t = b.GetType();
        FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic
                                         | BindingFlags.Instance); 
        foreach(FieldInfo fi in fields){
             Console.WriteLine(fi.Name);
        }
        Console.ReadLine();
    }
}

这未能找到现场B.a。

This fails to find the field B.a.

它甚至有可能做到这一点?显而易见的解决办法是在私人,继承字段转换为受保护的字段。然而,这是我的此刻控制。

Is it even possible to accomplish this? The obvious solution would be to convert the private, inherited fields to protected fields. This, however, is out of my control at the moment.

推荐答案

李说,你可以用递归做到这一点。

As Lee stated, you can do this with recursion.

private static void FindFields(ICollection<FieldInfo> fields, Type t) {
	var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

	foreach (var field in t.GetFields(flags)) {
		// Ignore inherited fields.
		if (field.DeclaringType == t)
			fields.Add(field);
	}

	var baseType = t.BaseType;
	if (baseType != null)
		FindFields(fields, baseType);
}

public static void Main() {
	var fields = new Collection<FieldInfo>();
	FindFields(fields, typeof(B));
	foreach (FieldInfo fi in fields)
		Console.WriteLine(fi.DeclaringType.Name + " - " + fi.Name);
}

这篇关于C#:访问继承的私人实例成员通过反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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