【问题标题】:C# accessing property values dynamically by property nameC# 通过属性名称动态访问属性值
【发布时间】:2012-12-07 15:37:55
【问题描述】:

我要解决的问题是如何编写一个将属性名称作为字符串接收的方法,并返回分配给该属性的值。

我的模型类声明类似于:

public class Foo
{
    public int FooId
    public int param1
    public double param2
}

在我的方法中,我希望做类似的事情

var property = GetProperty("param1)
var property2 = GetProperty("param2")

我目前正在尝试使用诸如

之类的表达式来做到这一点
public dynamic GetProperty(string _propertyName)
    {
        var currentVariables = m_context.Foo.OrderByDescending(x => x.FooId).FirstOrDefault();

        var parameter = Expression.Parameter(typeof(Foo), "Foo");
        var property = Expression.Property(parameter, _propertyName);

        var lambda = Expression.Lambda<Func<GlobalVariableSet, bool>>(parameter);

    }

这种方法是否正确,如果正确,是否可以将其作为动态类型返回?

答案是正确的,这太复杂了。现在解决办法是:

public dynamic GetProperty(string _propertyName)
{
    var currentVariables = m_context.Foo.OrderByDescending(g => g.FooId).FirstOrDefault();

    return currentVariables.GetType().GetProperty(_propertyName).GetValue(currentVariables, null);
}

【问题讨论】:

标签: c# dynamic lambda


【解决方案1】:
public static object ReflectPropertyValue(object source, string property)
{
     return source.GetType().GetProperty(property).GetValue(source, null);
}

【讨论】:

  • 我认为这会对具有索引器的属性抛出异常。
【解决方案2】:

你提供的样本太过分了。

您正在寻找的方法:

public static object GetPropValue( object target, string propName )
 {
     return target.GetType().GetProperty( propName ).GetValue(target, null);
 }

但是使用“var”、“dynamic”、“Expression”和“Lambda”......从现在起 6 个月后,您一定会迷失在这段代码中。坚持使用更简单的书写方式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    相关资源
    最近更新 更多