TLDR:这是如何编译的?
class A{};
Expression<Func<A, int>> e = x => 24; // I don't understant what makes this compile
// and what happens at this assignment
最小值是多少class E
能够编译E e = x => 24;
一些调查
class E {};
E e = x => 24;
Visual Studio 错误是“无法将 lambda 表达式转换为‘E’类型,因为它不是委托(delegate)类型”,这令人困惑,因为据我所知,委托(delegate)是这样声明的:
int delegate MyHandle();
而且我没有找到任何制作 class
的方法一个委托(delegate)。
此外,我查看了 Expression -> LambdaExpression -> Expression<TDelegate>
的元数据并且无法确定是什么语法/声明使 Expression<TDelegate>
像委托(delegate)一样行事。
我还尝试创建自己的 class E
模仿Expression<TDelegate>
而且我什至无法编译类
// basically a copy-paste of the metadata of `Expression<TDelegate>`
public sealed class E<TDelegate> : LambdaExpression
{
public TDelegate Compile() => default(TDelegate);
public TDelegate Compile(DebugInfoGenerator debugInfoGenerator) => default(TDelegate);
public TDelegate Compile(bool preferInterpretation) => default(TDelegate);
public Expression Update(Expression body, IEnumerable<ParameterExpression> parameters)
=> default(Expression);
protected override Expression Accept(ExpressionVisitor visitor) => null;
}
出现错误“'LambdaExpression' 不包含采用 0 个参数的构造函数”
上下文(可跳过):
我开始使用 Moq,因为我不能想当然,所以我想了解它是如何工作的/它是如何实现的。因此,这是关于此的一系列调查的第一部分。
我现在特别想了解
public class A
{
public virtual int Foo() => throw new NotImplementedException();
public virtual int Bar() => throw new NotImplementedException();
}
var a = new Mock<A>();
a.Setup(x => x.Foo()).Returns(24); // ??
Console.WriteLine(a.Object.Foo());
我试图了解信息“方法 Foo”是如何传递给 a
的
通过传递那个 lambda?据我所知,lambda 只是一个可调用对象,但不知何故神奇 a
知道 lambda 的实际主体,即如果您通过 x => 24
将抛出或 x => x.Foo() + x.Bar()
但会接受 x => x.Foo()
我看到了 Setup
参数类型为 Expression<Func<A, int>>
因此我现在的问题。
最佳答案
C# 规范对 System.Linq.Expressions.Expression<D>
进行了特殊处理;你不能为你自己的类型得到同样的待遇。
Expression trees permit lambda expressions to be represented as data structures instead of executable code. Expression trees are values of expression tree types of the form
System.Linq.Expressions.Expression<D>
, whereD
is any delegate type.
关于c# - linq Expression<TDelegate> 赋值如何在语言语法级别上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52446086/