使用反射从简单的类中获取字段值
我有一个类:
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) + "\r\n";
}
这是所需的结果:
a = A-val
b = B-val
不幸的是,这不起作用。请帮忙,谢谢。
I have a class:
class A {
public string a = "A-val" , b = "B-val";
}
I want to print the object members by reflection
//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) + "\r\n";
}
Here is the desired result:
a = A-val
b = B-val
Unfortunately this did not work. Please help, thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一旦修复并消除错误(缺少分号和错误的变量名称),您发布的代码确实可以工作 - 我刚刚尝试过,它显示了名称和值没有问题。
我的猜测是,实际上,您正在尝试使用非公开的字段。此代码:
...只会获取公共字段。您通常需要指定您还需要非公共字段:(
我希望您实际上没有公共字段,毕竟......)
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:
... will only get public fields. You would normally need to specify that you also want non-public fields:
(I hope you don't really have public fields, after all...)
请记住,当您编写如下字段时:
那么实际上您有以下代码(这就是反射看到的内容):
Remember when you write fields like :
Then actually you have this code(this is what reflection see) :
正如@Stanislav 所说,您必须记住编译器为属性生成的支持字段。如果您想排除这些字段,可以使用以下代码:
As @Stanislav say, you must keep in mind the backing fields generated by the compiler for properties. If you want to exclude these fields you can use the following code: