首先定义一个List类
列表是泛型类,可以存储任意类型,本文中,我们先创建BadGuy类,有两个公共字段 name
和 power
。
public class BadGuy :
{
public string name;
public int power;
public BadGuy(string newname, int newpower) //公共构造函数
{
name = newname;
power = newpower;
}
}
之后创建列表并分配内容。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SomeClasses : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
List<BadGuy> badGuys = new List<BadGuy>();
badGuys.Add(new BadGuy("Harvey", 50));
badGuys.Add(new BadGuy("Pip", 5));
badGuys.Add(new BadGuy("Magneto", 100));
badGuys.Add(new BadGuy("Nageto", 100));
badGuys.Insert(1,new BadGuy("Hippop",150));
badGuys.Sort(); //排序,需要Icomparable接口
foreach (BadGuy guy in badGuys)
{
print(guy.name + " " + guy.power);
}
badGuys.Clear();
}
依赖接口
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System; //IComparable的引用
public class BadGuy : IComparable<BadGuy>
{
public string name;
public int power;
public BadGuy(string newname, int newpower)
{
name = newname;
power = newpower;
}
// 以下为生序排列,CompareTo 方法返回正值时,比较对象大于other,0相等,负数反之
public int CompareTo(BadGuy other)
{
if (other ==null)
{
return 1;
}
return power - other.power ;
//降序排列
// return other.power - power;
}
}