我想解决的问题是如何编写一个方法,它将一个属性名称作为字符串接受,并返回分配给该属性的值。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);
}
您可以使用JST到System.Reflection.PropertyInfo从特定类型查找一个属性值的简单的方法。 http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx – Chris