为什么此方法组转换在 C# 7.2 及更低版本中不明确?
Why is this method group conversion ambiguous in C# 7.2 and lower?
给出以下 class:
public class Foo {
public Foo(int i, double d) {
Integer = i;
Double = d;
}
public int Integer {get;}
public double Double {get;}
private static Random rand = new Random();
public static Foo CreateRandom() => new Foo(rand.Next(1,101), rand.NextDouble());
}
还有这个用法:
void Main()
{
var items = Enumerable.Range(0, 50)
.Select(_ => Foo.CreateRandom());
Console.WriteLine(items.Sum(GetInteger)); // Fine
Console.WriteLine(items.Sum(GetDouble)); // Ambiguous
Console.WriteLine(items.Sum(x => x.Double)); // Also fine
Console.WriteLine(items.Sum((Func<Foo,double>)GetDouble)); // Cast required? Why?
int GetInteger(Foo item) => item.Integer;
double GetDouble(Foo item) => item.Double;
}
我想弄清楚为什么 GetDouble
委托转换被认为是不明确的,以及在这种情况下它与 labmda 表达式和对匿名委托的转换的确切区别。
编辑:
看起来这不会影响 C# 7.3,但会影响 7.2 及更低版本。添加本地方法之前的版本可能会受到 GetInteger 和 GetDouble 静态化的影响。
C# 7.3 中的新增功能
The following enhancements were made to existing features:
- You can test == and != with tuple types.
- You can use expression variables in more locations.
- You may attach attributes to the backing field of auto-implemented properties.
- Method resolution when arguments differ by in has been improved.
- Overload resolution now has fewer ambiguous cases.
最后一次修复是针对此问题的。在此之前,编译器在解析重载时遇到了更多困难。
这里是 link 来源。
给出以下 class:
public class Foo {
public Foo(int i, double d) {
Integer = i;
Double = d;
}
public int Integer {get;}
public double Double {get;}
private static Random rand = new Random();
public static Foo CreateRandom() => new Foo(rand.Next(1,101), rand.NextDouble());
}
还有这个用法:
void Main()
{
var items = Enumerable.Range(0, 50)
.Select(_ => Foo.CreateRandom());
Console.WriteLine(items.Sum(GetInteger)); // Fine
Console.WriteLine(items.Sum(GetDouble)); // Ambiguous
Console.WriteLine(items.Sum(x => x.Double)); // Also fine
Console.WriteLine(items.Sum((Func<Foo,double>)GetDouble)); // Cast required? Why?
int GetInteger(Foo item) => item.Integer;
double GetDouble(Foo item) => item.Double;
}
我想弄清楚为什么 GetDouble
委托转换被认为是不明确的,以及在这种情况下它与 labmda 表达式和对匿名委托的转换的确切区别。
编辑: 看起来这不会影响 C# 7.3,但会影响 7.2 及更低版本。添加本地方法之前的版本可能会受到 GetInteger 和 GetDouble 静态化的影响。
C# 7.3 中的新增功能
The following enhancements were made to existing features:
- You can test == and != with tuple types.
- You can use expression variables in more locations.
- You may attach attributes to the backing field of auto-implemented properties.
- Method resolution when arguments differ by in has been improved.
- Overload resolution now has fewer ambiguous cases.
最后一次修复是针对此问题的。在此之前,编译器在解析重载时遇到了更多困难。
这里是 link 来源。