我想将以下类从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);
}
}
答案 0 :(得分:4)
您可以通过继承IComparer<T>
来实施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);
}
}
答案 1 :(得分: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);
}
}