Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Created June 29, 2020 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ufcpp/6336a4c1033e431c6732e82e03029bc7 to your computer and use it in GitHub Desktop.
Save ufcpp/6336a4c1033e431c6732e82e03029bc7 to your computer and use it in GitHub Desktop.
mutable な参照型に Equals, GetHashCode を持たせるのはまずいという話
using System;
using System.Collections.Generic;
// mutable な「値比較」を書いてしまった場合…
class Mutable : IEquatable<Mutable>
{
public int X { get; set; }
public bool Equals(Mutable x) => X == x.X;
public override bool Equals(object obj) => obj is Mutable m && Equals(m);
public override int GetHashCode() => X;
}
class Program
{
static void Main()
{
var set = new HashSet<Mutable>();
for (int i = 0; i < 10; i++)
{
var x = new Mutable { X = i };
set.Add(x); // HashSet に登録した後で…
x.X = -1; // 値を書き換え
}
// 以下のコード、全部 false になる。
// 「自分自身の検索ができないオブジェクト」ができてる。
foreach (var x in set)
{
Console.WriteLine(set.Contains(x));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment