Dr *_* TJ 5 function return-type return-value dynamic-data c#-4.0
在C#中,我们有var数据类型但我们不能将它用作函数返回类型.
为什么这不可能?
public var myFunction()
{
var = some operations
}Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 13
我相信这部分是由于编译器的设计.Eric Lippert 在博客中写道,为什么字段不能使用隐式类型,我怀疑一些相同的参数适用于方法.
但无论如何,你很容易就会产生歧义.例如:
var Method1(bool callMethod2)
{
return callMethod2 ? Method2() : null;
}
var Method2()
{
return Method1(false);
}
Run Code Online (Sandbox Code Playgroud)
这个类型应该在这里?
一个更简单的例子:
var Method1(bool throwException)
{
if (!throwException)
{
return Method1(true);
}
throw new Exception("Bang!");
}
Run Code Online (Sandbox Code Playgroud)
不可否认,这种模糊性可能是不允许的,但我怀疑设计团队认为设计和实施的复杂性增加并不值得.不要忘记他们在资源有限的情况下运行 - 在var方法之间做出选择async/await,我会在心跳中选择后者.(不可否认,我已经选择了其他功能dynamic,但这是另一回事......)
请注意,返回类型推断的 lambda表达式执行的,所以它的想法是不是疯了.例如:
IEnumerable<string> x = new[] { "x", "y", "z" };
var result = x.Select(s => { return s.Length; }); // Long form
Run Code Online (Sandbox Code Playgroud)
在编译器执行重载决策时将编译器推断为完整类型的lambda表达式Select,将其转换为Func<string, int>.将相同的想法应用于方法并不是不可思议的 - 只是复杂的.