如何提取传递给Expression <Func <T,bool >>的属性名称和值?

DDi*_*ita 7 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 == "SomeValue");
Run Code Online (Sandbox Code Playgroud)

当我将其传递给Get扩展方法时,如何获得"PropertyName"和"SomeValue"?

Ray*_*Ray 12

我想这就是你所追求的

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


Console.WriteLine(name);
Console.WriteLine(value);
Run Code Online (Sandbox Code Playgroud)

输出:

PropertyName
SomeValue
Run Code Online (Sandbox Code Playgroud)

错误检查留给读者练习...