Get and set the field value by passing name

后端 未结 3 788
再見小時候
再見小時候 2020-12-10 20:49

I have a field in a class with a random name like:

class Foo {
    public string a2de = \"e2\"
}

I have the name of this field in another v

相关标签:
3条回答
  • 2020-12-10 21:10

    You'd have to use Reflection to access the variable by name. Like this:

    class Foo
    {
        int namedField = 1;
        string vari = "namedField"
    
        void AccessField()
        {
            int val = (int) GetType().InvokeMember(vari,
            BindingFlags.Instance | BindingFlags.NonPublic |
            BindingFlags.GetField, null, this, null);
            // now you should have 1 in val.
        }
    }
    
    0 讨论(0)
  • 2020-12-10 21:27

    You have to use reflection.

    To get the value of a property on targetObject:

    var value = targetObject.GetType().GetProperty(vari).GetValue(targetObject, null);
    

    To get the value of a field it's similar:

    var value = targetObject.GetType().GetField(vari).GetValue(targetObject, null);
    

    If the property/field is not public or it has been inherited from a base class, you will need to provide explicit BindingFlags to GetProperty or GetField.

    0 讨论(0)
  • 2020-12-10 21:28

    You can potentially do it with reflection (e.g. Type.GetField etc) - but that should generally be a last resort.

    Have you considered using a Dictionary<string, string> and using the "variable name" as the key instead?

    0 讨论(0)
提交回复
热议问题