设置要比较的类

问题描述 投票:-1回答:1
class A {
  int number;
  string text;
}

如果我想比较2个A类副本或想与这些泛型比较怎么办?

Dictioanry<A, int> dictionary = new Dictionary<A, int>
List<A> List = new List<A>
c# list class dictionary
1个回答
0
投票

Equals类本身中实现GetHashCodeA的任何一个>

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());
© www.soinside.com 2019 - 2024. All rights reserved.