C#通过属性名称动态访问属性值

18

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

我的模型类声明类似于:

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

你可以使用 System.Reflection.PropertyInfo 来查找特定类型的属性值。http://msdn.microsoft.com/zh-cn/library/system.reflection.propertyinfo.aspx - Chris
2个回答

36
public static object ReflectPropertyValue(object source, string property)
{
     return source.GetType().GetProperty(property).GetValue(source, null);
}

1
我认为对于具有索引器的属性,这将抛出异常。 - Phil Gan

7
你提供的样例太过冗长。
您需要的方法是:
public static object GetPropValue( object target, string propName )
 {
     return target.GetType().GetProperty( propName ).GetValue(target, null);
 }

但如果使用“var”、“dynamic”、“表达式”和“Lambda”等高级语法,你将在6个月后很难理解这段代码。建议使用更简单的方式编写代码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接