C#将比较类作为泛型类型传递

时间:2016-07-30 18:46:48

标签: c# generics

我是C#的新手。我试图创建一个堆结构,我想出了这个问题:如何将“compare-class”传递给我的堆结构?我的意思是,我想创建一个像:Heap<int, cmp<int>> heap = new Heap<int, cmp<int>>();这样的堆,其中“cmp”是一个比较类,它使堆成为优先级顺序(我在C ++中采用了priority_queue的想法)。我已经成功(我认为)制作了一个采用最大最小比较器的堆:

public class Heap<T, Priority>
    where Priority : IPriority<T>, new()
    where T : IComparable
{
    private List<T> storage = new List<T>();        
    private Priority HeapPriority = new Priority();
    private void UpHeap(int position)
    {            
        for(var i = position; i > 0; i = (i - 1) >> 1)
        {
            // Check whether storage[i] is more Priority than storage[(i - 1) >> 1]
            if (HeapPriority.MorePriority(storage[i], storage[(i - 1) >> 1])
                .CompareTo(storage[i]) == 0)
            {
                storage.Swap(i, (i - 1) >> 1);
            }
            else break;
        }
    }   
}

这是IPriority界面:

public interface IPriority<T>
    where T : IComparable
{
    T MorePriority(T a, T b);
}

我用过像这样的堆:

public class Min<T> : IPriority<T>
        where T : IComparable
    {
        public Min() { }
        public T MorePriority(T a, T b)
        {
            return a.CompareTo(b) <= 0 ? a : b;
        }
    }
static public void TestHeap()
    {
        var heap = new Heap<Pair<long, int>, Min<Pair<long, int>>>();            
        heap.Add(Pair<long, int>(10, 20));
        heap.Add(Pair<long, int>(21, 100));
        // ...
    }

但是我想要一个堆,以任何我想要的方式对项目进行排序,而不仅仅是最大最小订单。此外,有没有办法使用“Ipriority.MorePriority”作为静态方法?,因为它的工作方式与静态方法相同。谁能给我一些建议? 抱歉我的英语不好。

2 个答案:

答案 0 :(得分:2)

我建议将IComparer<T>视为依赖并将其传递给构造函数;像这样的东西:

  // You can create a heap of any type, right? 
  // But in some cases (e.g. Heap<Button>) you should provide a comparer:
  // how to compare Button instances   
  public class Heap<T> {
    //TODO: implement here Heap as well as Unheap method having IComparer<T> m_Comparer
    ...
    private IComparer<T> m_Comparer;

    // comparer = null - if comparer is not provided, try to use default one
    // if it's possible (e.g. in case of Heap<double>)
    public Heap(IComparer<T> comparer = null): base() {
      // Do we have a default comparer (e.g. for int, double, string)?
      if (null == comparer) 
        if (typeof(IComparable).IsAssignableFrom(typeof(T)) ||
            typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
          comparer = Comparer<T>.Default;

      if (null == comparer)
        throw new ArgumentNullException("comparer", string.Format(
          "There's no default comparer for {0} class, you should provide it explicitly.", 
          typeof(T).Name));

      m_Comparer = comparer;
    }
    ...
  }

所以你可以创建堆

  // heap of integers, default comparer
  Heap<int> heap1 = new Heap<int>();

  // heap of integers, custom comparer (via lambda)
  Heap<int> heap2 = new Heap<int>(Comparer<int>.Create((x, y) => -x.CompareTo(y)));

  // heap of Buttons, custome comparer 
  Heap<Button> heap3 = new Heap<Button>(Comparer<Button>.Create((x, y) => ...));

这将抛出异常Button类没有默认比较器

  Heap<Button> heapErr = new Heap<Button>();

答案 1 :(得分:0)

您应该使用IComparer<T>,这是.NET中所有集合使用的内容。例如:

public class Heap<T>
{
    private IComparer<T> comparer;
    private List<T> storage = new List<T>();     

    public Heap() : this(Comparer<T>.Default)
    {
    }

    public Heap(IComparer<T> comparer)
    {
        this.comparer = comparer;
    }

    private void UpHeap(int position)
    {            
        for(var i = position; i > 0; i = (i - 1) >> 1)
        {
            // Check whether storage[i] is more Priority than storage[(i - 1) >> 1]
            if (comparer.Compare(storage[i], storage[(i - 1) >> 1]) > 0)
            {
                storage.Swap(i, (i - 1) >> 1);
            }
            else break;
        }
    }   
}

这有几个好处:

  • 您不需要比较器的额外类型参数,在其他方法中引用堆时更方便。
  • 没有必要将T限制为IComparable
  • 但是,如果它确实实现ICompatable(如Int32那样),Comparer<T>.Default将使用该实现。