C# Reflection - Get field values from a simple class

后端 未结 3 1471
醉话见心
醉话见心 2020-11-27 07:10

I have a class:

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

I want to print the object members by reflection

相关标签:
3条回答
  • 2020-11-27 07:16

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

    0 讨论(0)
  • 2020-11-27 07:21

    Remember when you write fields like :

    public string VarName{ get; set;}
    

    Then actually you have this code(this is what reflection see) :

    private string _varName;
    public string get_VarName(){
    ....
    }
    public void set_VarName(strig value){
    ....
    }
    
    0 讨论(0)
  • 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:

    FieldInfo[] fields = data.GetType()
        .GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
        .Where(f => f.GetCustomAttribute<CompilerGeneratedAttribute>() == null)
        .ToArray();
    
    0 讨论(0)
提交回复
热议问题