按变量引用属性名称

问题描述 投票:1回答:4

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

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

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

c# reflection system.reflection
4个回答
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


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);

3
投票

我想你的意思是反思......

喜欢:

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

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.