Jon*_*ase 3 c# c#-7.0 visual-studio-2017 c#-7.2 c#-7.1
鉴于以下课程:
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());
}
Run Code Online (Sandbox Code Playgroud)
以及这种用法:
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;
}
Run Code Online (Sandbox Code Playgroud)
我试图找出为什么GetDouble委托转换被认为是不明确的,以及在这个上下文中它与labmda表达式和强制转换为匿名委托的确切原因.
编辑:看起来这不会影响C#7.3,但会影响7.2及更低版本.添加本地方法之前的版本可以通过使GetInteger和GetDouble静态来影响.
| 归档时间: |
|
| 查看次数: |
142 次 |
| 最近记录: |