how to input a string and get the same name property from a object? [duplicate]
Possible Duplicate:
Get property value from string using reflection in C#
say, classA
has properties A,B,C,D,E.. I wanna build a method StringToProperty
so that StringToProperty("A")
returns A.
I guess it can be done by reflection, but i have no knowledge of it now. Any simple examples?
THx, i will close it, plz vote to close
var type = classA.GetType();
PropertyInfo property = type.GetProperty("A");
var propertyValue = property.GetValue(anInstance, null);
Are you writing the method in the class that has the properties? If so just do the following:
public object StringToProperty(string prop)
{
switch(prop)
{
case "A":
return a;
case "B":
return b;
}
}
Or you can just use reflection if not:
Type type = classA.GetType();
return type.GetProperty(propertyString).GetValue(classAInstance, null);
If you do a very simple Google search you can find lots written about this!
Here's the first article I found that talks about exactly what you need.
And you could very easily write:
public object StringToProperty(string propertyName)
{
Type type = ClassA.GetType();
PropertyInfo theProperty = type.GetProperty(propertyName);
object propertyValue = theProperty.GetValue(yourClassAInstance, null);
return propertyValue;
}
精彩评论