如何是一个Func键< T>隐式转换为表达式来; Func键< T>&GT ;? [英] How is a Func<T> implicitly converted to Expression<Func<T>>?

查看:180
本文介绍了如何是一个Func键< T>隐式转换为表达式来; Func键< T>&GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白这里发生了什么:

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.

这篇关于如何是一个Func键&LT; T&GT;隐式转换为表达式来; Func键&LT; T&GT;&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆