I need to call a public property of a class based on the string value of its name, as I won't know until run time what properties are required. I'm trying to use reflections unsuccessfully. The class looks like this:
class FieldCalculation
{
public string MyValue
{
get
{
return "Test Data";
}
}
}
I think access the value of the property should look something like this:
FieldCalculation myClass = new FieldCalculation();
string value = myClass.GetType().GetProperty("MyValue");
Any help would be appreciated.
答案 0 :(得分:3)
You nearly had it. What you were doing was getting the property definition. You need to ask that property to get you the value, and you pass it the instance. This is the working code:
FieldCalculation myClass = new FieldCalculation();
string value = (string)myClass.GetType().GetProperty("MyValue").GetValue(myClass);