IComparable接口问题

luoyiaibaobao 2011-11-02 08:41:41
请问前辈们,为什么我下面的程序不能把名字排好序呢
class Student : IComparable
{
private string _name;
private int _age;
public Student(string name, int age)
{
_name = name;
_age = age;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public int Age
{
get { return _age; }
set { _age = value; }
}

public int CompareTo(object right)
{
if (!(right is Student))
{
throw new ArgumentException("参数必须为Student类型");

}
return _name.CompareTo(((Student)right)._name);//比较姓名
}
public override string ToString()
{
return _name;
}

}
class Program
{
static void Main()
{
Student[] arrs = new Student[4];
arrs[0] = new Student("张三", 5);
arrs[1] = new Student("李四", 6);
arrs[2] = new Student("王五", 7);
arrs[3] = new Student("马六", 8);
Array.Sort(arrs);
foreach (Student i in arrs)
{
Console.WriteLine(i);
}

}
}
...全文
44 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
luoyiaibaobao 2011-11-02
  • 打赏
  • 举报
回复
哦,果然没错,可能是我编译器出了点差错!感想了。
luoyiaibaobao 2011-11-02
  • 打赏
  • 举报
回复
什么没有关系啊?
星小野 2011-11-02
  • 打赏
  • 举报
回复
你写的
class Student : IComparable
{
private string _name;
private int _age;
public Student(string name, int age)
{
_name = name;
_age = age;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public int Age
{
get { return _age; }
set { _age = value; }
}

public int CompareTo(object right)
{
if (!(right is Student))
{
throw new ArgumentException("参数必须为Student类型");

}
return _name.CompareTo(((Student)right)._name);//比较姓名
}
public override string ToString()
{
return _name;
}

}
这些代码与下面的Main函数有什么关系??

你在Main函数中声明了一个数组,然后遍历输出,与上面写的没有关系。就是说你没用用到上面的代码。
xiongxyt2 2011-11-02
  • 打赏
  • 举报
回复
没错啊,是按名字升序
他是按照首字母比较的l<m<w<z

李四
马六
王五
张三

110,567

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧