class A {
int number;
string text;
}
如果我想比较2个A类副本或想与这些泛型比较怎么办?
Dictioanry<A, int> dictionary = new Dictionary<A, int>
List<A> List = new List<A>
在Equals
类本身中实现GetHashCode
和A
的任何一个>
public class A { //DONE: let assign number and text public A(int number, string text) { Number = number; Text = text; } // Let's have properties instead of fields public int Number {get;} public string Text {get;} public override bool Equals(object obj) { A other = obj as A; return (other != null) && string.Equals(Text, other.Text) && Number == other.Number; } public override int GetHashCode() { return (Text == null ? 0 : Text.GetHashCode()) ^ Number; } }
所以您可以放]]
Dictionary<A, int> dictionary = new Dictionary<A, int>();
或实施
IEqualityComparer<A>
:public class AEqualityComparer : IEqualityComparer<A> { public bool Equals(A x, A y) { if (ReferenceEquals(x, y)) return true; else if (null == x || null == y) return false; return string.Equals(x.Text, y.Sext) && x.Number == y.Number; } public int GetHashCode(A obj) { return (null == obj) ? 0 : (obj.Text == null ? 0 : obj.Text.GetHashCode()) ^ obj.Number; } }
在这种情况下,语法为
Dictionary<A, int> dictionary = new Dictionary<A, int>(new AEqualityComparer());