在接收表达式的函数中,如何检查表达式是否为成员访问lambda?
bool F<TSrc, TVal>(TSrc src, Expression<Func<TSrc, TVal>> exp) {
bool isMememberAccess = ???
if (!isMememberAccess) return false;
...
return true;
}因此:
var emp = new Employee();
var res = F(emp, x => x.FirstName); // returns true;
var org = new Organization();
var res = F(org, x => x.Sales.Manager.FirstName); // returns true;
int i=0;
var res = F(emp, x => i); // returns false - expression is not a member access我试图检查exp.Body.NodeType == ExpressionType.MemberAccess,但这两种情况下都返回true。
有什么帮助吗?
发布于 2020-03-11 00:32:48
捕获的lambda变量存储在生成的struct类型中,作为静态常量传入。您的表达式参数x => i大致相当于;
public struct locals
{
public int i;
}
var localState = new locals { i = i };
Expression.Lambda<Func<Employee, int>>(
Expression.MakeMemberAccess(
Expression.Constant(localState, typeof(locals)),
typeof(locals).GetField(nameof(locals.i))
),
Expression.Parameter(typeof(Employee),"x")
);如您所见,这还包括一个成员表达式。要证明的是,成员表达式基于表达式参数的类型。
bool F<TSrc, TVal>(TSrc src, Expression<Func<TSrc, TVal>> exp) {
var isMememberAccess = exp.Body is MemberExpression member
&& member.Expression is ParameterExpression parameter
&& parameter.Type == typeof(TSrc);
...https://stackoverflow.com/questions/60626908
复制相似问题