首先定义一个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;
}
}
这篇博客介绍了如何创建一个名为BadGuy的类,包含name和power两个字段,并用它来初始化一个List。接着展示了如何使用Insert方法向列表中添加元素,并通过实现IComparable接口对BadGuy对象按power属性进行排序。最后,博客通过foreach循环打印排序后的列表内容并清空列表。
432

被折叠的 条评论
为什么被折叠?



