2012-12-07 305 views
14

我想解决的问题是如何编写一个方法,它将一个属性名称作为字符串接受,并返回分配给该属性的值。C#通过属性名称动态访问属性值

我的模型类被声明类似于:

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

,并从我的方法中我希望通过使用表达式这样做类似这样的

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

我目前正在做这个事情as

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

您可以使用JST到System.Reflection.PropertyInfo从特定类型查找一个属性值的简单的方法。 http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx – Chris

回答

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

我认为这将抛出一个例外,有一个索引器的属性。 –

6

你与你所提供的取样方式过分去。

您正在寻找的方法:

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

但使用“VAR”和“动态”和“表达”和“拉姆达” ......你一定会迷失在这个码6几个月后。坚持写它