Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

C# Reflection - Get field values from a simple class

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) + "
";
}

Here is the desired result:

a = A-val
b = B-val

Unfortunately this did not work. Please help, thanks.

question from:https://stackoverflow.com/questions/7649324/c-sharp-reflection-get-field-values-from-a-simple-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

... 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...)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...