lambda表达式和var关键字在C# [英] lambda expression and var keyword in c#

查看:187
本文介绍了lambda表达式和var关键字在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
C#为什么不能匿名方法被分配到VAR?

我有以下用C#语句

Func <int, int, int> add = (x, y) => x + y;



但是,当我与以下替换左侧声明

But when I am replacing left hand side statement with following

var add = (x, y) => x + y;



我收到编译器错误(无法lambda表达式分配给一个隐式类型的局部变量)。为什么?

推荐答案

由于编译器无法弄清楚什么键入RHS已经从

Because the compiler can't figure out what type the RHS has from

var add = (x, y) => x + y;

这支持 + 运营商的任何类型候选并且由于x和y的类型不约束是相同类型的。还有的退出了很多可能的的+ 可能被使用,因此可能的类型集x和y是相当大的,但要能够确定附加的类型的运营商,编译器需要能够以该组减少到只有一个类型为x和一个用于Y(不完全真实的,它可能是双方的基类和派生类也适合)和还甚至如果编译器可以计算出类型x和y或您指定的类型让我们说 INT 你还是会离开的事实,都
表达式来;函数功能:LT; INT,INT,INT>> Func键< INT,INT,INT> 都是可能的类型添加

Any type that supports the + operator is a candidate and since the type of x and y is not constraint to be of the same type. There's quit a lot of possible + operators that could be used and therefore the set of possible types for x and y is rather large but to be able to determine the type of add, the compiler need to be able to reduce the set to just one type for x and one for y (not exactly true, it might be that both a base class and a derived class would fit) and still even if the compiler could figure out the type for x and y or that you specified the types to let's say int you'd still be left with the fact that both Expression<Func<int,int,int>> and Func<int,int,int> are possible types for add

有对如何减少组可能的类型的多个选项。编译器可以尝试看看如何添加以后使用,但不会(和潜在想不出类型的出即使它)

There are multiple options for how to reduce the set of possible types. The compiler could try to look at how add is used later but doesn't (and potentially couldn't figure the types out even if it did)

这篇关于lambda表达式和var关键字在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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