首先我们先看下微软官方是咋定义这个接口了,大概翻译是这样了定义值类型或类实现的通用方法,以创建确定实例相等性的特定于类型的方法。
如我需要判断结构体内三个参数和另外一个结构体的三个参数是否相等
public struct UniqueId : IEquatable<UniqueId> { public long Part1 { get; } public long Part2 { get; } public long Part3 { get; } public UniqueId(long part1, long part2, long part3) { Part1 = part1; Part2 = part2; Part3 = part3; } public override string ToString() => $"{Part1}.{Part2}.{Part3}"; public bool Equals(UniqueId other) => Part1 == other.Part1 && Part2 == other.Part2 && Part3 == other.Part3; public override bool Equals(object obj) => obj is UniqueId other && Equals(other); }
static void Main(String[] args) { UniqueId uniqueId1 = new UniqueId((long)111, (long)222, (long)333); UniqueId uniqueId2 = new UniqueId((long)444, (long)555, (long)666); Console.WriteLine(uniqueId1.Equals(uniqueId2)); Console.ReadLine(); }
大家也可以写一个自己Equals扩展方法