Class field addresses by name



  • Let's say there's a class.

    class A 
    {
        public int Age;
        public string Name;
    }
    

    What needs to be done to enable the initialization of the class field through instance["Age"] = 5;Is that possible?



  • This can be done by an indexer ([]and reflexia. Example code:

    public object this[string fieldName]
    {
        get
        {
            var field = this.GetType().GetField(fieldName);
            return field.GetValue(this);
        }
        set
        {
            var field = this.GetType().GetField(fieldName);
            field.SetValue(this, value);
        }
    }
    

    This code works for all specimen fields. If you need to put it in like this and the static fields, you need to change the code. Validation (e.g. the name of the existing field, or that the type of value to be determined corresponds to the field type) and the cashing of the field list (to request only once).


    Although it is best to use the fields or properties themselves. Or replace your class with a dictionary where the key is the name of the field/ownship.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2