Comparer<T>、IComparer<T> 和 Comparison<T> 之间的链接

Sve*_*ana 2 c# generics delegates

我是 C# 新手。我需要编写一个代码来对 T 数组进行排序。我在选择比较方法时遇到了问题。
根据我的任务,我应该提供方法,使用 Comparer<T>IComparer<T>Comparison<T>
我正在寻找一种解决方案,它可以将一种方法引入另一种方法,因此我避免对Comparer<T>,IComparer<T>和中的每一个重复相同的逻辑Comparison<T>

我知道,这Comparison<T>可能会被“重新创建”为Comparer<T>with Comparer<T>.Create,但是如何使Comparer<T>IComparer<T>可以互换呢?

到目前为止,方法的原型如下所示。

public T[] Sort<T>(T[] toSort) where T : System.IComparable<T>;
    
public T[] Sort<T>(T[] toSort, IComparer<T> comparer);
    
public T[] Sort<T>(T[] toSort, Comparer<T> comparer);
    
public T[] Sort<T>(T[] toSort, Comparison<T> comparison);
Run Code Online (Sandbox Code Playgroud)

Gur*_*ron 7

Comparer<T>实现IComparer<T>接口(简单来说 - 它是一个IComparer<T>):

public abstract class Comparer<T> : IComparer<T>, IComparer
Run Code Online (Sandbox Code Playgroud)

所以它可以在任何地方使用,IComparer<T>无需任何努力。即,您可以删除public T[] Sort<T>(T[] toSort, Comparer<T> comparer);,但仍然可以将 的实例Comparer<T>作为参数传递给public T[] Sort<T>(T[] toSort, IComparer<T> comparer);

阅读更多: