C# 如何提取传递到表达式中的属性名称和值<;Func<;T、 布尔>>;?

C# 如何提取传递到表达式中的属性名称和值<;Func<;T、 布尔>>;?,c#,lambda,C#,Lambda,假设我有这样一种方法: public static List<T> Get<T>(this SomeObject<T>, Expressions<Func<T,bool>> e){ //get the property name and value they want to check is true / false ... } TheObject().Get(x => x.PropertyName == "SomeValu

假设我有这样一种方法:

public static List<T> Get<T>(this SomeObject<T>, Expressions<Func<T,bool>> e){

//get the property name and value they want to check is true / false
...

}

TheObject().Get(x => x.PropertyName == "SomeValue");
publicstaticlist-Get(这是SomeObject,表达式e){
//获取要检查的属性名称和值是否为true/false
...
}
TheObject().Get(x=>x.PropertyName==“SomeValue”);

当我将“PropertyName”和“SomeValue”传递到get扩展方法中时,如何获取它们?

我想这就是您想要的

BinaryExpression expression = ((BinaryExpression)e.Body);
string name = ((MemberExpression)expression.Left).Member.Name;
Expression value = expression.Right;


Console.WriteLine(name);
Console.WriteLine(value);
输出:

PropertyName
SomeValue
错误检查留给读者作为练习

 var expressionBody= e.Body.ToString();
将返回如下所示的字符串:

//"(x.PropertyName == \"SomeValue\")"

还有更准确的方法(例如编译),但是编译表达式的性能对您的要求非常糟糕,
System.Web.Mvc
名称空间可能会帮助您重新编译。看看

他说“我怎么才能得到”PropertyName“和”SomeValue" . 使用我的解决方案,他可以在不编译表达式的情况下得到这个结果。我错了吗?是的,您总是可以在不编译表达式的情况下得到所需的结果。事实上,编译它不会得到期望的结果。我之前的意思是,你不知道他们为什么需要这个,所以你无法判断性能是否真的很差或足够。好的,可能我没有适当地解释我自己。关于提取多个参数和运算符,你知道有什么资源:(c=>c.FirstName.Contains(“A”)&&c.Address.Place==“Beach”| c.Address.Place==“山”)。我看着这棵树,它让我大吃一惊。不,对不起,我只是试着看看这棵树。