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