为什么不能用VAR返回类型声明一个函数? [英] Why is it not possible to declare a function with VAR return type?
问题描述
在C#中,我们有 var
数据类型,但我们不能将其用作函数返回类型。
为什么不可能? / p>
In C#, we have var
data type but we can't use it as functions return type.
Why this is not possible?
public var myFunction()
{
var = some operations
}
推荐答案
我认为这部分是由于编译器的设计。 Eric Lippert 博客了解为什么字段不能使用隐式类型,我怀疑一些相同的参数保存方法。
I believe it's partly due to the design of the compiler. Eric Lippert blogged about why fields can't use implicit typing, and I suspect some of the same arguments hold for methods.
但是你可能很容易结束歧义中。例如:
But you could easily end up with ambiguity anyway. For example:
var Method1(bool callMethod2)
{
return callMethod2 ? Method2() : null;
}
var Method2()
{
return Method1(false);
}
这里应该是什么类型?
What should the type be here?
一个更简单的例子:
var Method1(bool throwException)
{
if (!throwException)
{
return Method1(true);
}
throw new Exception("Bang!");
}
诚然,这种歧义可以简单地被禁止,但我怀疑设计团队认为设计和实施的复杂性增加不值得。不要忘记它们使用有限的资源运行 - 给方法和 async / await
之间的 var
,我会选择后者在心跳。 (诚然,还有其他的功能,我会选择,而不是动态
,但这是一个不同的事情...)
Admittedly this sort of ambiguity could simply be disallowed, but I suspect that the design team felt that the added complexity of both design and implementation wasn't worth the benefit. Don't forget that they're running with limited resources - given a choice between var
for methods and async/await
, I'd pick the latter in a heartbeat. (Admittedly there are other features I'd have picked instead of dynamic
, but that's a different matter...)
请注意,返回类型推断是对lambda表达式执行,所以它的想法不是疯了。例如:
Note that return type inference is performed for lambda expressions, so the very idea of it isn't crazy. For example:
IEnumerable<string> x = new[] { "x", "y", "z" };
var result = x.Select(s => { return s.Length; }); // Long form
编译器在执行重载分辨率时推断出完整类型的lambda表达式选择
,将其转换为 Func< string,int>
。将同样的想法应用于方法并不难想象 - 只是复杂。
There the compiler infers the complete type of the lambda expression when it performs overload resolution on Select
, converting it to a Func<string, int>
. It's not inconceivable to apply the same ideas to methods - just complicated.
这篇关于为什么不能用VAR返回类型声明一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!