且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从C#中的字符串创建基于动态Lambda的Linq表达式?

更新时间:2023-11-07 18:43:16

此处提出了类似的问题:

A similar question was asked here:

是否有一种简单的方法可以将(lambda表达式)字符串解析为Action委托?

据我了解,此动态查询"实际上是一个框架,用于在不使用lambda表达式的情况下传递对Where子句的限制.

As I understand it, this 'Dynamic Query' is actually a framework for passing in restrictions for a Where clause without using a lambda expression.

这样做的意义在于,lambda表达式不是动态方法,它们是匿名方法.如果您查看过一个程序集,您会发现您的lambda表达式将转换为带有任何***变量作为字段的闭包.该类具有一个签名与您的签名相匹配的方法,在调用时分配了字段变量.

The significance of that is that lambda expressions are not dynamic methods, they're anonymous methods. If you ever take a look in an assembly, you'll see that your lambda expressions are converted into closures with any free variables as fields. The class has a method with a signature matching yours, field variables are assigned at the point of invocation.

对此进行考虑的一种好方法是,它意味着lambda表达式在编译时由c#编译器解释,并且变量是通过在运行时从此类实例化一个对象来解析的.

One good way to think about that is that it implies that your lambda expression is interpreted by the c# compiler at compile-time, and variables are resolved by instantiating an object from this class at run-time.

为证明这一点,请考虑以下因素:

To demonstrate this, consider the following:

var myLambda = x => x * x

您会注意到这是行不通的.这是因为,为了创建相关的类/方法,编译器必须在编译时知道x的类型.

You'll notice this doesn't work. That's because, in order to create the related class/method, the compiler must know, at compile-time, the type of x.

所有这些都很重要,因为lambda表达式的概念在运行时不存在于CLR(与代码中的形式相同).看起来像lambda表达式的字符串就是那个……

All of this is important because the notion of a lambda expression doesn't exist at the CLR at run-time (in the same form it is in code). A string that looks like a lambda expression is exactly that...