0Pricing
C# Academy · レッスン

レコード風の型と値ベースの等価性(パターン)

レコードのような値ベースの等価性を実装します。Equals/GetHashCodeをオーバーライドし、IEquatable を実装し、==/!=演算子を追加して、型を不変に保ちます。

「レコード風の型と値ベースの等価性(パターン)」はCoddyKit上の無料C# Academyレッスンです。 これはレッスン2/3です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはC# Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 C# Academyコースには全3レッスンが含まれています。

レコード風の概要

目標:C# 6 でオブジェクトを値(レコード風)として比較できるようにします。

  • 不変データ
  • EqualsとGetHashCodeをオーバーライドします
  • IEquatable<T>を実装します
  • 任意で==/!=を定義します

参照等価性の問題

クラスは既定で参照によって比較されます。同じデータを持つ2つのオブジェクトでも等しいとはみなされません。

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を通じてフィールドで比較されますが、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>を実装します。
  • 利便性のために==/!=を追加します。
  • 等価性の判定とハッシュ処理で一貫したフィールドを使用します。

レコード風の等価性に必要なこと

C# 6 でクラスを値(レコード風)として動作させるには、何を行う必要があるでしょうか?

まとめ

まとめ:C# 6 では、レコード風の型を手作業で構築します。不変データ、IEquatable<T>、正しいEquals/GetHashCode、そして(任意で)==/!=を実装します。これらをセットやディクショナリで安全に使用します。

よくある質問

「レコード風の型と値ベースの等価性(パターン)」レッスンは無料ですか?

はい。「レコード風の型と値ベースの等価性(パターン)」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、C# Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 C# Academyコースには全3レッスンが含まれています。

「レコード風の型と値ベースの等価性(パターン)」で何を学びますか?

レコードのような値ベースの等価性を実装します。Equals/GetHashCodeをオーバーライドし、IEquatable を実装し、==/!=演算子を追加して、型を不変に保ちます。 ブラウザで直接実行するハンズオンコードでC# Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

C# Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのC# Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/3です。

「レコード風の型と値ベースの等価性(パターン)」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このC# Academyレッスンでコードを書いて実行できますか?

はい。すべてのC# Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. 構造体:値セマンティクスと不変パターン
  2. レコード風の型と値ベースの等価性(パターン)
  3. 列挙型と[Flags]
← C# Academyに戻る