IComparable
一种特定于类型的通用比较方法,值类型或类通过实现此方法对特认定进行排序
IComparable的作用是提供了一种比较两个对象的特定类型的方法。这是必需的如果您想要为对象提供任何排序功能。视为IComparable提供您的对象的默认排序次序。例如对于如果您有一个您的类型的对象的数组,并在该数组上调用Sort方法IComparable在排序过程中提供对象的比较。实现IComparable接口时, 必须实现CompareTo方法
此接口由具有可排序值的类型实现。它要求实现类型定义单个方法CompareTo,该方法指示当前实例在排序顺序中的位置是位于同一类型的另一个对象之前、之后还是与其位置相同。
compareTo
public int compareTo(Integer anotherInteger)在数字上比较两个Integer对象。
如果该 Integer 等于 Integer 参数,则返回 0 值;如果该 Integer 在数字上小于 Integer 参数,则返回值-1;如果 Integer 在数字上大于 Integer 参数,则返回整数1
using System;
public class CropRenderInfo:IComparable<CropRenderInfo>
{
public int cropID = 0;
public int dailyRemainPlantTimes = 10;
public int CompareTo(CropRenderInfo other)
{
if(this.dailyRemainPlantTimes <= 0)
{
if(other.dailyRemainPlantTimes <= 0)
{
if(this.cropID > other.cropID)
{
return 1;
}
else if(this.cropID == other.cropID)
{
return 0;
}
else
{
return -1;
}
}
else
{
return 1;
}
}
else
{
if (other.dailyRemainPlantTimes <= 0)
{
return -1;
}
else
{
if (this.cropID > other.cropID)
{
return 1;
}
else if (this.cropID == other.cropID)
{
return 0;
}
else
{
return -1;
}
}
}
}
}
排序时用sort直接排序
private void InitCropRenderInfoList()
{
cropRenderInfoList = new List<CropRenderInfo>();
for (int i = 0; i < 15; i++)
{
CropRenderInfo cropRenderInfo = new CropRenderInfo();
cropRenderInfo.cropID = i + 1;
CropInfo cropInfo = DataManager.Instance.GetCropInfo(cropRenderInfo.cropID);
cropRenderInfo.dailyRemainPlantTimes = PlayerInfo.Instance.GetPropCount(cropInfo.taskItemID);
cropRenderInfoList.Add(cropRenderInfo);
}
cropRenderInfoList.Sort();
}