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:
(For properties, use
PropertyInfo)Note that
valueis an object; in order to do anything useful with it, you’ll need to cast it to some class or interface (or usedynamicin C# 4).