Created
June 29, 2020 12:35
-
-
Save ufcpp/6336a4c1033e431c6732e82e03029bc7 to your computer and use it in GitHub Desktop.
mutable な参照型に Equals, GetHashCode を持たせるのはまずいという話
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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