C#反思 - 从一个简单的类获取的字段值 [英] C# Reflection - Get field values from a simple class
问题描述
我有一个类:
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
不幸的是这没有奏效。请帮忙,谢谢。
Unfortunately this did not work. Please help, thanks.
推荐答案
在固定摆脱错误(缺少分号和一个糟糕的变量名)时,code你已经发布的确实的工作 - 我只是尝试它和它没有任何问题表现出的名称和值
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.
我的猜测是,在现实中,你要使用的不是公共领域。这code:
My guess is that in reality, you're trying to use fields which aren't public. This code:
FieldInfo[] fields = data.GetType().GetFields();
...只会得到的公共的领域。通常你需要指定你还需要非公共字段:
... 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屋!