List集合中存在數個玩家Playerthis
實現排序:排序
按防護力升序,若相同則按攻擊力降序接口
方法有兩種:class
1. 類外定義Sort方法 實現接口 IComparerobject
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
使用時: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;
}new
使用: players.Sort();return