List集合中存在数个玩家Player
实现排序:
按防御力升序,若相同则按攻击力降序
方法有两种:
1. 类外定义Sort方法 实现接口 IComparer
public class Sort : IComparer<Player>
{
public int Compare(Player a, Player b)
{
if (a is Player && b is Player)
{
if (a.defence == b.defence)
{
return b.attack - a.attack;
}
else
{
return a.defence - b.defence;
}
}
return 0;
}
}
使用时:List集合 players---> players.Sort(new Sort());
2.在玩家类Player 实现接口 : IComparable
public int CompareTo(object obj)
{
if(obj is Player)
{
Player other = obj as Player;
if(this.defence == other.defence)
{
return other.attack - this.attack;
}
else
{
return this.defence - other.defence;
}
}
return 0;
}
使用: players.Sort();