Given a string with the same name of an object field, how can I get the reference to the object field?
For example, say I pass in a string called "field1" to the GetFieldByStr method, and the object has an field name field1, how can I get a reference to the field1 object? I'm assuming using reflection somehow.
class Example {
private FieldExample attr1;
void GetFieldByStr(String str) {
// We get passed in "field1" as a string, now I want
// to get the field1 attribute.
}
}
You need to use Reflection:
FieldInfo field = typeof(Example).GetField(str);
object value = field.GetValue(this);
(For properties, use PropertyInfo)
Note that value is an object; in order to do anything useful with it, you'll need to cast it to some class or interface (or use dynamic in C# 4).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With