C#6 改进的重载解析 - 说明?
C#6's Improved overload resolution - clarification?
在 C#6 的所有新特性中,(对我来说)最神秘的特性是 "improved overload resolution".
可能是因为我 couldn't find 与 info/examples/explanation 有关。
The only two remaining features not discussed are support for defining
a custom Add extension method to help with collection initializers,
and some minor but improved overload resolution
正在查看 roslyn wiki
There are a number of small improvements to overload resolution, which
will likely result in more things just working the way you’d expect
them to. The improvements all relate to “betterness” – the way the
compiler decides which of two overloads is better for a given
argument.
所以我问:
问题:
改进的重载解析 究竟如何在 C#6 中发挥作用? 它与 C#5 有何不同(示例?文档?)
我相信这里的意思是 "better betterness" 规则,即 documented in the Roslyn github repo。
示例代码:
using System;
class Test
{
static void Foo(Action action) {}
static void Foo(Func<int> func) {}
static int Bar() { return 1; }
static void Main()
{
Foo(Bar);
}
}
使用 C# 5 编译器(例如在 c:\Windows\Microsoft.NET\Framework\v4.0.30319\
中)会产生两个错误:
Test.cs(11,9): error CS0121: The call is ambiguous between the following methods or properties:
'Test.Foo(System.Action)' and 'Test.Foo(System.Func)'
Test.cs(11,13): error CS0407: 'int Test.Bar()' has the wrong return type
使用 C# 6 编译器,可以正常编译。
同样对 lambda 表达式使用精确匹配,这会在 C# 5 编译器中产生不明确的重载错误,但在 C# 6 中不会:
using System;
class Test
{
static void Foo(Func<Func<long>> func) {}
static void Foo(Func<Func<int>> func) {}
static void Main()
{
Foo(() => () => 7);
}
}
在 C#6 的所有新特性中,(对我来说)最神秘的特性是 "improved overload resolution".
可能是因为我 couldn't find 与 info/examples/explanation 有关。
The only two remaining features not discussed are support for defining a custom Add extension method to help with collection initializers, and some minor but improved overload resolution
正在查看 roslyn wiki
There are a number of small improvements to overload resolution, which will likely result in more things just working the way you’d expect them to. The improvements all relate to “betterness” – the way the compiler decides which of two overloads is better for a given argument.
所以我问:
问题:
改进的重载解析 究竟如何在 C#6 中发挥作用? 它与 C#5 有何不同(示例?文档?)
我相信这里的意思是 "better betterness" 规则,即 documented in the Roslyn github repo。
示例代码:
using System;
class Test
{
static void Foo(Action action) {}
static void Foo(Func<int> func) {}
static int Bar() { return 1; }
static void Main()
{
Foo(Bar);
}
}
使用 C# 5 编译器(例如在 c:\Windows\Microsoft.NET\Framework\v4.0.30319\
中)会产生两个错误:
Test.cs(11,9): error CS0121: The call is ambiguous between the following methods or properties:
'Test.Foo(System.Action)' and 'Test.Foo(System.Func)'
Test.cs(11,13): error CS0407: 'int Test.Bar()' has the wrong return type
使用 C# 6 编译器,可以正常编译。
同样对 lambda 表达式使用精确匹配,这会在 C# 5 编译器中产生不明确的重载错误,但在 C# 6 中不会:
using System;
class Test
{
static void Foo(Func<Func<long>> func) {}
static void Foo(Func<Func<int>> func) {}
static void Main()
{
Foo(() => () => 7);
}
}