在C#中将字符串计算为属性

我有一个存储在字符串中的属性…说Object Foo有一个属性Bar ,所以要获取我将调用的Bar属性的值。

 Console.Write(foo.Bar); 

现在说我把"Bar"存储在一个字符串变量中……

 string property = "Bar" Foo foo = new Foo(); 

我如何使用property获取foo.Bar的值?

我是如何在PHP中使用它的

 $property = "Bar"; $foo = new Foo(); echo $foo->{$property}; 

 Foo foo = new Foo(); var barValue = foo.GetType().GetProperty("Bar").GetValue(foo, null) 

你会使用reflection:

 PropertyInfo propertyInfo = foo.GetType().GetProperty(property); object value = propertyInfo.GetValue(foo, null); 

调用中的null用于索引属性,而不是您拥有的属性。

你需要使用reflection来做到这一点。

这样的事应该照顾你

 foo.GetType().GetProperty(property).GetValue(foo, null);