【问题标题】:Refer to a property name by variable通过变量引用属性名称
【发布时间】:2012-11-08 15:28:39
【问题描述】:

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

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

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

【问题讨论】:

  • 很难理解你想要完成什么。
  • 你可以使用 System.Reflection 来做到这一点,例如参考这个stackoverflow.com/questions/619767/…。
  • 我很好奇为什么你会做这样的事情而不是使用像属性这样的属性?
  • @Jared 如果可能的话,你应该相信它会有用。
  • 完全是@T.Todua。现在我已经习惯了极其复杂的反射,因为我已经发布了这个,我意识到他们是如何忽视这个问题的。

标签: c# reflection system.reflection


【解决方案1】:

简单:

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

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

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

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。

【讨论】:

  • 这些都不适用于我的动态变量。它是一个 Dapper 对象。 data.GetType() 抛出错误。
  • @tukaef 请您详细说明为什么 GetType() 在代码中是必需的?我可以看到它是,我只是不明白为什么我不能直接获取对象的属性,为什么我还需要 GetType() 方法?请提供链接或解释,在此先感谢!
【解决方案2】:

我认为你的意思是反射:

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

【讨论】:

    【解决方案3】:

    不是按照您的建议,但是是可行的。您可以使用 dynamic 对象(甚至只是带有属性索引器的对象),例如

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

    或者使用反射:

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

    【讨论】:

    • 这不适用于我的动态变量。它是一个 Dapper 对象。 data.q1 有效,但 data["q1"] 无效。这会引发错误。
    【解决方案4】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多