将委托传递给 Sort()

Passing Delegate to Sort()

在 Enrico Buonanno 所著的“Functional C#”一书中,第 16 页给出了以下代码:

namespace System
{
    public delegate int Comparison<in T>(T x, T y);
}

var list = Enumerable.Range(1, 10).Select(i => i * 3).ToList();
list // => [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
Comparison<int> alphabetically = (l, r)
=> l.ToString().CompareTo(r.ToString());
list.Sort(alphabetically);
list // => [12, 15, 18, 21, 24, 27, 3, 30, 6, 9]

然而,当在 REPL 中执行时,这不会产生任何有用的东西。

error CS1503: Argument "1": Konvertierung von "Comparison<int>" in "System.Collections.Generic.IComparer<int>" nicht möglich.

怎么了?

Comparison is an existing delegate in .NET so you don't need to declare your own. Just remove this declaration and corresponding List.Sort(Comparison<T>) will be invoked - compare this and this.