先说一下函数Equals和运算符"=="二者的区别:
1. 对比值类型:
”==“ 与 ”Equals“ 一样,都是对比变量值
C#已经重写了string的”==“和”Equals“,对比结果与值类型一致
2. 对比引用类型:
引用类型:内容存储在堆,堆地址存储在栈
”==“ 对比引用地址,即栈内存储的堆地址
”Equals“ 对比对象,即堆上存储的对象内容
举一个栗子来说明重写,需要的可以按此方式扩展啦~
一条2D线段,用起点终点来表示,判断线段相等需要判断起点终点都相等,这个比较简单,就不上代码啰嗦啦。重点是通过重写Equals函数,更方便的实现判断。
//定义线段类
class OverrideLine
{
public Vector2 A { get; private set; }
public Vector2 B { get; private set; }
public OverrideLine(Vector2 pointA, Vector2 pointB)
{
A = pointA;
B = pointB;
}
//比较自定义对象
//重写Equals, 判断线段相等
public override bool Equals(object obj)
{
if (obj is OverrideLine)
{
var edge = (OverrideLine)obj;
return (edge.A == A && edge.B == B) || (edge.B == A && edge.A == B);
}
return false;
}
//重写了Equals函数,同时也必要重写GetHashCode函数
//判断Equals时,两个对象的GetHashCode()返回值相等是且Equals()函数的必要条件
//即:GetHashCode()返回值相等,且Equals()函数体内部逻辑返回值为true,则Equals()返回true
//重写GetHashCode
public override int GetHashCode()
{
return A.GetHashCode() ^ B.GetHashCode();
}
//重写==
public static bool operator ==(OverrideLine line01, OverrideLine line02)
{
return line01.Equals(line02);
}
//运算符!=要与==一起重写
public static bool operator !=(OverrideLine line01, OverrideLine line02)
{
return !(line01 == line02);
}
//
//扩展,重写ToString,自定义Log输出的格式内容
public override string ToString()
{
return string.Format("[" + A + "->" + B + "]");
}
}
//在定义一个普通的类,以作对比
class NormalLine
{
public Vector2 A { get; private set; }
public Vector2 B { get; private set; }
public NormalLine(Vector2 pointA, Vector2 pointB)
{
A = pointA;
B = pointB;
}
}
//接下来打印一下对比结果
public class OverrideEquals : MonoBehaviour
{
//对比值类型:
//”==“ 与 ”Equals“ 一样,都是对比变量值
//C#已经重写了string的”==“和”Equals“,对比结果与值类型一致
//对比引用类型:
//引用类型:内容存储在堆,堆地址存储在栈
//”==“ 对比引用地址,即栈内存储的堆地址
//”Equals“ 对比对象,即堆上存储的对象内容
void Start()
{
OverrideLine line01 = new OverrideLine(Vector2.zero, Vector2.one);
OverrideLine line02 = new OverrideLine(Vector2.zero, Vector2.one);
List<OverrideLine> overrideLineList = new List<OverrideLine>();
overrideLineList.Add(line01);
Debug.Log(line01.Equals(line02)); //true
Debug.Log(line01 == line02); //true
Debug.Log(overrideLineList.Contains(line02)); //true
NormalLine line03 = new NormalLine(Vector2.zero, Vector2.one);
NormalLine line04 = new NormalLine(Vector2.zero, Vector2.one);
List<NormalLine> normalLineList = new List<NormalLine>();
normalLineList.Add(line03);
Debug.Log(line03.Equals(line04)); //false
Debug.Log(line03 == line04); //false
Debug.Log(normalLineList.Contains(line04)); //false
}
}