C#6的改进重载 - 澄清? [英] C#6's Improved overload resolution - clarification?
问题描述
在所有的C#6,最神秘的功能(对我)的新功能是的改进重载的
Among all the new features in C#6, the most mysterious feature (to me) is the "improved overload resolution".
也许是因为我的找不到的相关信息/例子/它的解释。
Maybe it's because I couldn't find related info/examples/explanation about it.
没有讨论的唯一剩余的两个功能是定义
A自定义添加扩展方法帮助集合初始化支持,
和一些小的改进,但重载
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维基的
有一些小的改进重载决议,其中
很可能会导致更多的事情只是工作,你会期望
的方式来。这些改进都涉及betterness - 的
编译器决定哪些两个重载的是对于给定的
论点更好的方式
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的(例?文档?)的
How exactly is the Improved overload resolution comes into play in C#6? And how it is different from C#5 (Example? Documentation?)
推荐答案
我相信在这里的意思是好betterness规则,是的在罗斯林GitHub库记录
I believe what is meant here is the "better betterness" rules which are 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使用C#5编译器(例如: $ C> C:\Windows\Microsoft.NET\Framework\v4.0.30319\ )这给了两个错误:
test.cs中(11,9):错误CS0121:呼叫是以下方法或属性之间暧昧:结果
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;测试包含.foo(System.Action)'和'Test.Foo(System.Func)'结果
test.cs中(11,13):错误CS0407:'诠释Test.Bar()'有错误的返回类型
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编译器,它编译罚款。
Using the C# 6 compiler, it compiles fine.
同样使用lambda表达式精确匹配,这会产生与C#5编译暧昧过载错误,但不能用于C#6:
Likewise using exact matching for lambda expressions, this generates an ambiguous overload error with the C# 5 compiler, but not for 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的改进重载 - 澄清?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!