C# 反射 - 从一个简单的类中获取字段值 [英] C# Reflection - Get field values from a simple class

查看:36
本文介绍了C# 反射 - 从一个简单的类中获取字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课:

class A {
    public string a = "A-val" , b = "B-val";
}

我想打印对象成员通过反射

//Object here is necessary.
Object data = new A();
FieldInfo[] fields = data.GetType().GetFields();
String str = "";
foreach(FieldInfo f in fields){
    str += f.Name + " = " + f.GetValue(data) + "
";
}

这是想要的结果:

a = A-val
b = B-val

不幸的是,这不起作用.请帮忙,谢谢.

Unfortunately this did not work. Please help, thanks.

推荐答案

一旦修复以消除错误(缺少分号和错误的变量名称),您发布的代码就可以 工作 - 我刚刚尝试过,它显示的名称和值没有问题.

Once fixed to get rid of the errors (lacking a semi-colon and a bad variable name), the code you've posted does work - I've just tried it and it showed the names and values with no problems.

我的猜测是,实际上,您正在尝试使用不公开的字段.这段代码:

My guess is that in reality, you're trying to use fields which aren't public. This code:

FieldInfo[] fields = data.GetType().GetFields();

... 只会得到 public 字段.您通常需要指定您还需要非公共字段:

... will only get public fields. You would normally need to specify that you also want non-public fields:

FieldInfo[] fields = data.GetType().GetFields(BindingFlags.Public | 
                                              BindingFlags.NonPublic | 
                                              BindingFlags.Instance);

(我希望你没有真的有公共字段,毕竟......)

(I hope you don't really have public fields, after all...)

这篇关于C# 反射 - 从一个简单的类中获取字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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