如何是一个Func键< T>隐式转换为表达式来; Func键< T>> ;?
我不明白这里发生了什么:
I don't understand what is happening here:
这两个行的编译:
Func<object> func = () => new object();
Expression<Func<object>> expression = ()=>new object();
但是,这并不:
But this doesn't:
expression = func;
有上没有一个隐含的经营者 LambdaExpression
或表达式来; TDelegate>
可以转换一个委托的表达,所以别的东西一定要发生的事情,使分配工作。这是什么
There isn't an implicit operator on LambdaExpression
or Expression<TDelegate>
that converts a delegate to the expression, so something else must be happening to make the assignment work. What is it?
这不是通常意义上的隐式转换 - 这是一个编译器的把戏。编译器检测哪一个从上下文预期,然后编译它无论是作为一个代表(在你的类隐藏方法)或表达式(一段代码,通过调用 System.Linq.Expressions.Expression
)。
It's not an implicit conversion in the usual sense - it's a compiler trick. The compiler detects which one is expected from the context, and then compiles it either as a delegate (a hidden method on your class) or as an expression (a chunk of code that constructs the expression by calling the methods on System.Linq.Expressions.Expression
).
这是你不能lambda表达式直接分配给类型的变量的原因对象
或 VAR
,除其他外,因为编译器必须能够知道你是否意味着委托或表达。
This is the reason you can't directly assign a lambda expression to a variable of type object
or var
, among other things, because the compiler has to be able to know whether you mean a delegate or an expression.