不同的子类在List中是能够正常存储的,但是在存储时都需要以父类型存储进去,即List的类型为父类,而Add()中的类型可以声明为实际使用的类型:
`Prop newProp = new ChildProp(); newProp = prop; //prop为需要add的参数,并且已知prop为子类型ChildProp转换而来 PropInKs.Add(newProp);
`
- 虽然能够正常存储,但是在使用过程中只能使用父类的方法,而想要使用子类的方法时,为了避免类型判断,可以在父类中加入用于判定类型的标签,根据标签取出。
- List.Sort()自定义排序。
因为List存储了不同子类的参数,所有需要自定义父类的Sort排序,以Prop类为例:
public class Prop : MonoBehaviour, IComparer<Prop> {
public string Decription;
public int ID;
public float Weight;
public PropType type;
public int Compare(Prop x, Prop y) {
return x.ID.CompareTo(y.ID);
}
}
Prop需要继承Icomparer接口,并实现Compare方法,Compare有三个返回值,1为大于,0为等于,-1为小于,Sort默认为升序。