Suppose there is a class
class A { public int Age; public string Name; } What you need to do to be able to initialize the field instance of the class through the instance["Age"] = 5; And is it possible?
Suppose there is a class
class A { public int Age; public string Name; } What you need to do to be able to initialize the field instance of the class through the instance["Age"] = 5; And is it possible?
This can be done using an indexer ( [] ) and reflection. Sample 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 instance fields. If you need to install incl. and static fields - you need to change the code. Also, in a good way, you need to add a validation (for example, that the name of an existing field is specified, or that the type of the value being set corresponds to the field type) and caching the list of fields (to request them only once).
Although it is best to use the fields themselves or properties. Or replace your class with a dictionary, where the key will be the name of the field / property.
initialize the field class instance through instance ["Age"] = 5; And is it possible?
You can simply write instance.Age = 5; .
To do this, use dynamic and ExpandoObject . An example is here .
reimplement the operator [] something like this:
class a { public int age; public string name; public object this[int i] { get { return age[i]; } set { age[i] = value; } } } age[i] ? - GrundySource: https://ru.stackoverflow.com/questions/469677/
All Articles
public int Age {get;set;}? and let me correct you not the properties but the fields - Bald Nov.