سؤال

I want to convert the following class from java to 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);
    }    
}
هل كانت مفيدة؟

المحلول 2

Why not just implement the non-generic IComparer interface directly? That is, the non-generic Java interface converts to the non-generic C# interface:

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);
    }
}

نصائح أخرى

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);
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top