evaluate a string as a property in C#
I have a property stored in a string... say Object Foo
has a property Bar
, so to get the value of 开发者_JS百科the Bar
property I would call..
Console.Write(foo.Bar);
Now say that I have "Bar"
stored in a string variable...
string property = "Bar"
Foo foo = new Foo();
how would I get the value of foo.Bar
using property
?
How I'm use to doing it in PHP
$property = "Bar";
$foo = new Foo();
echo $foo->{$property};
Foo foo = new Foo();
var barValue = foo.GetType().GetProperty("Bar").GetValue(foo, null)
You would use reflection:
PropertyInfo propertyInfo = foo.GetType().GetProperty(property);
object value = propertyInfo.GetValue(foo, null);
The null
in the call there is for indexed properties, which is not what you have.
You need to use reflection to do this.
Something like this should take care of you
foo.GetType().GetProperty(property).GetValue(foo, null);
精彩评论