类Comparer <t>:目的是存在IComparer.Compare的显式实现

时间:2019-04-15 14:44:52

标签: c# comparison

存在目的是IComparer.Comp的显式实现在Comparer<T>类的实现中。 如果我实现了public abstract int Compare (T x, T y)的原因以及调用int IComparer.Compare (object ObjX, object ObjY)的原因,请考虑到必须将ObjX和ObjY强制转换为T类型(在其他情况下为ArgumentException)。

第12行和第13行将产生相同的动作;

class Program
{
    static void Main(string[] args)
    {
      IComparer iRefCommon = (IComparer)new BoxLengthFirst();
      object obj1 = new Box(2, 6, 8);
      object obj2 = new Box(10, 12, 14);
      int resulCompare = iRefCommon.Compare((Box)obj1, (Box)obj2); //line12
      resulCompare = (new BoxLengthFirst()).Compare(new Box(2, 6, 8),
             new Box(10, 12, 14)); //line13
    }
}

public class BoxLengthFirst : Comparer<Box> 
{
    public override int Compare(Box x, Box y)
    {
        if (x.Length.CompareTo(y.Length) != 0)
        {
            return x.Length.CompareTo(y.Length);
        }
        .....
        else
        {
            return 0;
        }
    }
}

public class Box : IComparable, IComparable<Box>
{
    public Box(int h, int l, int w)
    {
        this.Height = h;
        this.Length = l;
        this.Width = w;
    }
    public int Height { get; private set; }
    public int Length { get; private set; }
    public int Width { get; private set; }

    public int CompareTo(object obj)
    {
     ....
    }
    public int CompareTo(Box other)
    {
       ....
    }
}

1 个答案:

答案 0 :(得分:-1)

尝试以下操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;


namespace ConsoleApplication108
{
    class Program
    {
        static void Main(string[] args)
        {
            Box a = new Box(1, 1, 1);
            Box b = new Box(2, 2, 2);

            int c = a.CompareTo(b);

        }

    }
    public class Box : IComparable
    {
        public Box() { }
        public Box(int h, int l, int w)
        {
            this.Height = h;
            this.Length = l;
            this.Width = w;
        }
        public int Height { get; private set; }
        public int Length { get; private set; }
        public int Width { get; private set; }

        public int CompareTo(object obj)
        {
             return CompareTo((Box)obj);
        }
        public int CompareTo(object obj1, object obj2)
        {
             return ((Box)obj1).CompareTo((Box)obj2);
        }
        public int CompareTo(Box other)
        {
            int results = this.Height.CompareTo(other.Height);
            if (results != 0)
            {
                results = this.Length.CompareTo(other.Length);
                if (results != 0)
                {
                    results = this.Width.CompareTo(other.Width);
                }
            }
            return results;
        }
    }

}
相关问题