1

我想将以下类从 java 转换为 C#:

public class ValueComparator implements Comparator{

    @Override
    public int compare(Object ob1, Object ob2){
        int retval = 0;
        if ( ob1 instanceof DataCol && ob2 instanceof DataCol ){
            DataCol c1 = (DataCol) ob1;
            DataCol c2 = (DataCol) ob2;
            if( c1.value < c2.value ) retval = 1;
            if( c1.value > c2.value ) retval = -1;
        } else {
            throw new ClassCastException("ValueComparator: Illegal arguments!");
        }
        return(retval);
    }    
}
4

2 回答 2

5

You can implement IComparer<T> by inheriting from Comparer<T>.

class DataColComparer:Comparer<DataCol>
{
    public override int Compare(DataCol x, DataCol y)
    {
       if(ReferenceEquals(x,y))
         return 0;
       if(x==null)
         return -1;
       if(y==null)
         return +1;
       return Comparer<TValue>.Default.Compare(y.Value, x.Value);
    }
}
于 2012-12-07T14:30:25.307 回答
1

为什么不直接实现非泛型 IComparer 接口?也就是说,非泛型 Java 接口转换为非泛型 C# 接口:

public class ValueComparator : System.Collections.IComparer
{
    public int Compare(object ob1, object ob2)
    {
        int retval = 0;
        if (ob1 is DataCol && ob2 is DataCol)
        {
            DataCol c1 = (DataCol) ob1;
            DataCol c2 = (DataCol) ob2;
            if (c1.value < c2.value) retval = 1;
            if (c1.value > c2.value) retval = -1;
        }
        else
        {
            throw new ClassCastException("ValueComparator: Illegal arguments!");
        }
        return (retval);
    }
}
于 2012-12-07T15:25:26.610 回答