按变量引用属性名称

时间:2012-11-08 15:28:39

标签: c# reflection system.reflection

有没有办法用变量引用属性名称?

场景:对象A具有公共整数属性X和Z,所以......

public void setProperty(int index, int value)
{
    string property = "";

    if (index == 1)
    {
        // set the property X with 'value'
        property = "X";
    }
    else 
    {
        // set the property Z with 'value'
        property = "Z";
    }

    A.{property} = value;
}

这是一个愚蠢的例子,所以请相信,我对此有用。

4 个答案:

答案 0 :(得分:22)

易:

a.GetType().GetProperty("X").SetValue(a, value);

请注意,如果GetProperty("X")的类型没有名为“X”的属性,则null会返回a

要在您提供的语法中设置属性,只需编写扩展方法:

public static class Extensions
{
    public static void SetProperty(this object obj, string propertyName, object value)
    {
        var propertyInfo = obj.GetType().GetProperty(propertyName);
        if (propertyInfo == null) return;
        propertyInfo.SetValue(obj, value);
    }
}

并像这样使用它:

a.SetProperty(propertyName, value);

<强> UPD

请注意,这种基于反射的方法相对较慢。为了更好的性能,请使用动态代码生成或表达式树有很好的库可以为你做这个复杂的东西。例如,FastMember

答案 1 :(得分:4)

不是你的建议方式,但是是可行的。您可以使用dynamic对象(或者甚至只是具有属性索引器的对象),例如

string property = index == 1 ? "X" : "Z";
A[property] = value;

或者通过使用反射:

string property = index == 1 ? "X" : "Z";
return A.GetType().GetProperty(property).SetValue(A, value);

答案 2 :(得分:3)

我认为你的意思是反思......

像:

PropertyInfo info = myObject.GetType().GetProperty("NameOfProperty");
info.SetValue(myObject, myValue);

答案 3 :(得分:0)

我很难理解你想要实现的目标......如果你试图分别确定属性和值,并且在不同的时间,你可以将属性设置在委托中。

public void setProperty(int index, int value)
{
    Action<int> setValue;

    if (index == 1)
    {
        // set property X
        setValue = x => A.X = x;
    }
    else
    {
        // set property Z
        setValue = z => A.Z = z;
    }

    setValue(value);
}
相关问题