问题描述
参照,据我了解,下面是不是在C#支持:
VAR FUNC =(X,Y)=>将Math.log(X)+将Math.log(Y);
不过,我可以创建一个方法,函数功能
的格式为:
公共静态Func键< T,T,T> FUNC< T>(FUNC< T,T,T&F)的温度= GT; F;
然后执行:
VAR func =函数<双>((X,Y)=>将Math.log(X)+将Math.log(Y));
这将编译就好了。然而,对于不同类型的参数和返回值的lambda表达式,事情就变得奇怪。举例来说,如果我有一个方法:
公共静态Func键< T1,T2,T3> FUNC&所述的T1,T2,T3>(FUNC&下; T1,T2,T3和F)的温度= GT; F;
我可以为例子做的:
VAR func =函数((双X,双Y)=> ${X + Y});
和太会编。因此,C#编译器似乎能够推断出返回类型的lambda。但是,以下不会编译:
VAR func =函数((X,Y)=>将Math.log( X)+将Math.log(Y));
编译器似乎是不能够推断出类型第X
和是
从它们在体内使用的方式。
所以,我的问题:什么是对lambda表达式类型推断的明确规则;会出现什么编译器推断出,哪些不是吗?
The definitive rules are in the specification. If you want to look at the implementation, you can find it easily enough in the Roslyn sources; I commented it pretty heavily, anticipating that there would be questions. Note that in particular the comment starting around line 110 is relevant to your question; study this carefully if you want a deep understanding of how lambda type inference works.
Consider compiling the compiler yourself in debug mode; you can then use the Dump
method at breakpoints to describe the state of the type inference engine as it goes. I used this to facilitate more rapid debugging, and when considering extensions to the algorithm. (Some of which are still in the code, commented out.)
That is far too broad a question to answer definitively. But the basic action with respect to the examples in your question is:
- Bounds on type parameters are inferred from ordinary arguments matched with formal parameter types.
- Lambdas where all formal parameter types of the lambda are inferred or known have their return types inferred
- The previous step is repeated until the algorithm fails to make progress or deduces a contradiction.
I recorded a video -- ten years ago now -- explaining all this step by step but apparently it is no longer on MSDN. I am vexed.
这篇关于什么是C#编译器使用的lambda表达式解析类型的规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!