我试图解决的问题是如何编写一个方法,该方法接收一个属性名字符串作为参数,并返回分配给该属性的值。
我的模型类声明类似于:
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);
}