为什么不能用 VAR 返回类型声明函数? [英] Why is it not possible to declare a function with VAR return type?
问题描述
在 C# 中,我们有 var
数据类型,但我们不能将其用作函数返回类型.
为什么这是不可能的?
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 博客 关于为什么 fields 不能使用隐式类型,我怀疑一些相同的参数适用于方法.
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!");
}
诚然,这种模棱两可的情况是完全不允许的,但我怀疑设计团队认为设计和实现增加的复杂性不值得从中受益.不要忘记它们运行时资源有限——如果在方法的 var
和 async/await
之间进行选择,我会立即选择后者.(诚然,我会选择其他功能而不是 dynamic
,但那是另一回事...)
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
编译器在对 Select
执行重载解析时推断 lambda 表达式的完整类型,将其转换为 Func
.将相同的想法应用于方法并非不可想象 - 只是复杂.
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屋!