7

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

场景:对象 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

4 回答 4

31

简单的:

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

请注意,如果 type of没有名为“X”的属性,则GetProperty("X")返回。nulla

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

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

请注意,这种基于反射的方法相对较慢。为了获得更好的性能,请使用动态代码生成或表达式树。有很好的库可以为你做这些复杂的事情。例如,快速会员

于 2012-11-08T15:31:28.940 回答
5

我认为你的意思是反射:

PropertyInfo info = myObject.GetType().GetProperty("NameOfProperty");
info.SetValue(myObject, myValue);
于 2012-11-08T15:30:39.047 回答
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);
于 2012-11-08T15:32:01.263 回答
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);
}
于 2012-11-08T15:45:17.027 回答