在 PHP 中,我可以使用可变变量来动态访问类属性,如下所示:
class foo
{
public $bar = 'test';
}
$a = 'bar';
$obj = new foo;
echo $obj->$a; // output 'test'
我怎样才能在 C# 中做这样的事情?
最佳答案
假设:
public class Foo
{
public String bar { get; set; }
}
// instance that you want the value from
var instance = new Foo { bar = "baz" };
// name of property you care about
String propName = "bar";
您可以使用:
// Use Reflection (ProperyInfo) to reference the property
PropertyInfo pi = instance.GetType()
.GetProperty(propName);
// then use GetValue to access it (and cast as necessary)
String valueOfBar = (String)pi.GetValue(instance);
最终结果:
Console.WriteLine(valueOfBar); // "baz"
让事情变得更简单:
public static class PropertyExtensions
{
public static Object ValueOfProperty(this Object instance, String propertyName)
{
PropertyInfo propertyInfo = instance.GetType().GetProperty(propertyName);
if (propertyInfo != null)
{
return propertyInfo.GetValue(instance);
}
return null;
}
public static Object ValueOfProperty<T>(this Object instance, String propertyName)
{
return (T)instance.ValueOfProperty(propertyName);
}
}
并给出与上述相同的假设:
// cast it yourself:
Console.WriteLine((String)instance.ValueOfProperty(propName)); // "baz"
// use generic argument to cast it for you:
Console.WriteLine(instance.ValueOfProperty<String>(propName)); // "baz"
关于c# - 使用可变变量调用对象的属性,如 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18593690/