C# 在C中将字符串作为属性求值#

C# 在C中将字符串作为属性求值#,c#,properties,C#,Properties,我有一个存储在字符串中的属性。。。假设对象Foo有一个属性Bar,那么要获取我将调用的Bar属性的值 Console.Write(foo.Bar); 现在假设我在字符串变量中存储了“Bar” string property = "Bar" Foo foo = new Foo(); 如何使用property获取foo.Bar的值 我是如何习惯用PHP做的 您可以使用反射: PropertyInfo propertyInfo = foo.GetType().GetProperty(proper

我有一个存储在字符串中的属性。。。假设对象
Foo
有一个属性
Bar
,那么要获取我将调用的
Bar
属性的值

Console.Write(foo.Bar);
现在假设我在字符串变量中存储了
“Bar”

string property = "Bar"

Foo foo = new Foo();
如何使用
property
获取
foo.Bar
的值

我是如何习惯用PHP做的


您可以使用反射:

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

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

您需要使用反射来完成此操作

像这样的东西应该会照顾好你

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