c# - 使用可变变量调用对象的属性,如 PHP

标签 c#

在 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/

相关文章:

c# - Restsharp oAuth 2 腿身份验证错误 : Invalid signature for signature method HMAC-SHA1

c# - 使用 Moq 设置 Mock 存储库

c# - 任何人都知道一个好的随机数生成器

c# - 当ID包含@时,通过Sense chrome扩展程序对Elasticsearch的请求中断

c# - 寻找 .NET 数学方程式编辑器和求解器控件

c# - 将 C# 数据集导出到文本文件

c# - 不同域上的不同网站,一个 .NET MVC 应用程序?

c# - 当我们没有该 dll 的源代码时,如何在 Visual Studio 中调试非托管 dll?

c# - CE5 中的触摸屏阻止来自外围设备的数据流量

c# - 如何从 xml 构建 .xsd 文件?