如何使用自定义的比较方法对点列表进行排序?
using System;
using System.Collections;
using System.Collections.Generic;
public class Point : IComparer<Point>
{
public int x;
public int y;
public Point(int x_Point, int y_Point)
{
x = x_Point;
y = y_Point;
}
public int Compare(Point a, Point b)
{
if (a.x == b.x && a.y == b.y)
return 0;
if (a.y < b.y)
return -1;
if (a.y == b.y && a.x < b.x)
return -1;
return 1;
}
}
下面的代码在 AL.sort(( 处抛出错误。
"无法比较数组中的两个元素。" "参数异常:至少一个对象必须实现 IComparable">
我不知道为什么。我在积分课上描述自己的比较方法有误吗?
public class ArrayListTest
{
public static void Main(string[] args)
{
ArrayList AL = new ArrayList();
Random R = new Random();
for (int i = 0; i < 10; i++)
{
Point p = new Point(R.Next(50), R.Next(50));
AL.Add(p);
}
PrintValues(AL);
AL.Sort();
PrintValues(AL);
}
}
你最好使用IComparable<>
界面。
"要排序的对象将实现IComparable,而要对对象进行排序的类将实现IComparer。
来源:IComparable和IComparer之间的区别
public class Point : IComparable<Point>
{
public int x;
public int y;
public Point(int x_Point, int y_Point)
{
x = x_Point;
y = y_Point;
}
public int CompareTo(Point other)
{
if (this.x == other.x && this.y == other.y)
return 0;
if (this.y < other.y)
return -1;
if (this.y == other.y && this.x < other.x)
return -1;
return 1;
}
}
public static void Main()
{
var AL = new List<Point>(); // ditch the ArrayList for good... ;-)
Random R = new Random();
for (int i = 0; i < 10; i++)
{
Point p = new Point(R.Next(50), R.Next(50));
AL.Add(p);
}
PrintValues(AL);
AL.Sort();
PrintValues(AL);
}