使用像PHP这样的变量变量来调用对象的属性

时间:2013-09-03 13:32:00

标签: c#

在PHP中,我可以使用变量变量来动态访问类属性,如下所示:

class foo 
{
    public $bar = 'test';
}

$a = 'bar'; 
$obj = new foo;

echo $obj->$a; // output 'test'

我怎样才能在C#中做这样的事情?

2 个答案:

答案 0 :(得分:2)

假设:

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"

答案 1 :(得分:0)

你不会做那样的事情,C#不支持variable variables。您可以使用reflection to get a property value,但这是另一个野兽,因为您将失去强类型等等。很简单,它归结为为什么您想要这样做吗?在大多数情况下,您通常不需要,而不是运行时的值解析。

您可以做的是使用基于字符串的字典(即Dictionary<string, string>)来按键索引您的值。

然后你可以这样做:

class Foo
{
    public Dictionary<string, string> values = new Dictionary<string, string>();

    public Foo()
    {
        values["foo"] = "test";
    }
}

var test = "foo";
var foo = new Foo();
Console.WriteLine(foo.values[test]);