using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
internal class People
{
public string name;
public People(string name) {
this.name = name;
}
}
// Start is called before the first frame update
void Start()
{
List<People> list = new List<People>();
var t1 = new People("张三");
var t2 = new People("张三");
list.Add(t1);
bool isContain = list.Contains(t2);
bool isRemoved = list.Remove(t2);
Debug.Log(isContain); // false
Debug.Log(isRemoved); // false
}
}
如上所示,因为People
类没有实现IEquatable接口
,调用集合Contains、Remove方法时使用Object类的Equals() 方法比较这些元素,默认实现
代码对值类型按位比较,对引用类型只比较其引用(内存地址),t1和t2是两个不同引用对象,所以无法用t2查询或删除集合中的t1。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
internal class People:IEquatable<People>
{
public string name;
public People(string name) {
this.name = name;
}
public bool Equals(People other)
{
return name.Equals(other.name);
}
}
// Start is called before the first frame update
void Start()
{
List<People> list = new List<People>();
var t1 = new People("张三");
var t2 = new People("张三");
list.Add(t1);
bool isContain = list.Contains(t2);
bool isRemoved = list.Remove(t2);
Debug.Log(isContain); // true
Debug.Log(isRemoved); // true
}
}
如上所示,在People
类实现了IEquatable接口并重写Equals方法, t1和t2具有相同name,因此可以用t2成功
查询并删除掉集合中的t1。