0Pricing
C# Academy · 课时

记录式类型与基于值的相等性(模式)

像记录一样实现基于值的相等性:重写 Equals/GetHashCode,实现 IEquatable ,添加 ==/!= 运算符,并保持类型不可变。

记录式类型与基于值的相等性(模式) 是 CoddyKit 上的免费 C# Academy 课时。 这是第 2 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C# Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C# Academy 课程共包含 3 节课。

类记录概览

目标:在 C# 6 中让对象按值进行比较(类记录形式)。

  • 不可变数据
  • 重写 Equals 和 GetHashCode
  • 实现 IEquatable<T>
  • 可选:定义 ==/!=

reference 相等性问题

类默认按reference比较。具有相同数据的两个对象并不相等。

using System;

public class PersonRef
{
  public string First;
  public string Last;
}

public class Program
{
  public static void Main(string[] args)
  {
    PersonRef a = new PersonRef { First = "Ada", Last = "Lovelace" };
    PersonRef b = new PersonRef { First = "Ada", Last = "Lovelace" };

    Console.WriteLine("Reference Equals? " + object.ReferenceEquals(a, b)); // false
    Console.WriteLine("== (default)? " + (a == b)); // false (same as ReferenceEquals for classes)
  }
}

类记录形式的模式

使类不可变,并实现 IEquatable<T>、Equals、GetHashCode 和 ==/!=,使相等性取决于数据。

using System;

// Immutable, value-based equality
public sealed class Person : IEquatable<Person>
{
  public string First { get; private set; }
  public string Last  { get; private set; }

  public Person(string first, string last)
  {
    if (string.IsNullOrEmpty(first)) throw new ArgumentException("first");
    if (string.IsNullOrEmpty(last))  throw new ArgumentException("last");
    First = first; Last = last;
  }

  // "With" helper for copy-on-change
  public Person WithFirst(string first) { return new Person(first, Last); }
  public Person WithLast(string last)   { return new Person(First, last); }

  public bool Equals(Person other)
  {
    if (object.ReferenceEquals(other, null)) return false;
    if (object.ReferenceEquals(this, other)) return true;
    return string.Equals(First, other.First) && string.Equals(Last, other.Last);
  }

  public override bool Equals(object obj)
  {
    return Equals(obj as Person);
  }

  public override int GetHashCode()
  {
    unchecked
    {
      int h = 17;
      h = h * 31 + (First == null ? 0 : First.GetHashCode());
      h = h * 31 + (Last  == null ? 0 : Last.GetHashCode());
      return h;
    }
  }

  public static bool operator ==(Person a, Person b)
  {
    if (object.ReferenceEquals(a, b)) return true;
    if ((object)a == null || (object)b == null) return false;
    return a.Equals(b);
  }

  public static bool operator !=(Person a, Person b) { return !(a == b); }
}

public class Program
{
  public static void Main(string[] args)
  {
    Person p1 = new Person("Ada", "Lovelace");
    Person p2 = new Person("Ada", "Lovelace");
    Console.WriteLine("Value Equals? " + (p1 == p2)); // true
    Person p3 = p1.WithLast("King");
    Console.WriteLine("After With: " + (p1 == p3));   // false
  }
}

结构体相等性模式

结构体默认通过 ValueType.Equals 按 fields 比较,但实现 IEquatable<T> 可以清晰表达意图并明确哈希行为。

using System;

public struct Point2 : IEquatable<Point2>
{
  public int X;
  public int Y;

  public Point2(int x, int y) { X = x; Y = y; }

  public bool Equals(Point2 other)
  {
    return X == other.X && Y == other.Y;
  }

  public override bool Equals(object obj)
  {
    if (!(obj is Point2)) return false;
    return Equals((Point2)obj);
  }

  public override int GetHashCode()
  {
    unchecked { return (X * 397) ^ Y; }
  }

  public static bool operator ==(Point2 a, Point2 b) { return a.Equals(b); }
  public static bool operator !=(Point2 a, Point2 b) { return !a.Equals(b); }
}

public class Program
{
  public static void Main(string[] args)
  {
    Point2 a = new Point2(1, 2);
    Point2 b = new Point2(1, 2);
    Console.WriteLine("Struct value equality: " + (a == b)); // true
  }
}

作为键的值对象

当值对象作为 Dictionary 的键时,正确的 Equals/GetHashCode 可以确保查找成功。

using System;
using System.Collections.Generic;

public sealed class Email : IEquatable<Email>
{
  public string Address { get; private set; }
  public Email(string address)
  {
    if (string.IsNullOrEmpty(address)) throw new ArgumentException("address");
    Address = address.Trim().ToLowerInvariant();
  }

  public bool Equals(Email other)
  {
    if (object.ReferenceEquals(other, null)) return false;
    return Address == other.Address;
  }

  public override bool Equals(object obj) { return Equals(obj as Email); }

  public override int GetHashCode()
  {
    return Address == null ? 0 : Address.GetHashCode();
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    Dictionary<Email, string> owners = new Dictionary<Email, string>();
    owners[new Email("User@Mail.com")] = "Ada";
    Console.WriteLine(owners.ContainsKey(new Email("user@mail.com"))); // true
  }
}

相等性检查清单

检查清单:

  • 保持数据不可变。
  • 重写 Equals 和 GetHashCode。
  • 实现 IEquatable<T>,以进行类型安全且快速的比较。
  • 添加 ==/!= 以便使用。
  • 在相等性比较和哈希计算中使用一致的 fields。

类记录形式的相等性要求

快速检查:要让类在 C# 6 中表现得像值(类记录形式),必须做什么?

回顾

回顾:在 C# 6 中,您需要手动构建类记录形式的类型:不可变数据、IEquatable<T>、正确的 Equals/GetHashCode,以及(可选的)==/!=。安全地在集合和字典中使用它们。

常见问题解答

「记录式类型与基于值的相等性(模式)」课时是免费的吗?

是的 — 「记录式类型与基于值的相等性(模式)」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C# Academy 课程的其余内容,请升级到 CoddyKit PRO。 C# Academy 课程共包含 3 节课。

「记录式类型与基于值的相等性(模式)」这节课中我会学到什么?

像记录一样实现基于值的相等性:重写 Equals/GetHashCode,实现 IEquatable ,添加 ==/!= 运算符,并保持类型不可变。 你通过在浏览器中直接运行的动手代码来练习 C# Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 C# Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 C# Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 3 节。

「记录式类型与基于值的相等性(模式)」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 C# Academy 课中编写并运行代码吗?

能。每节 C# Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 结构体:值语义与不可变模式
  2. 记录式类型与基于值的相等性(模式)
  3. 枚举与 [Flags]
← 返回 C# Academy