-3

我有一个像这样的对象:

public class MyObject {
    public string firstname { get; set; }
    public string lastname { get; set; }
    public int age { get; set; }
    public string occupation { get; set; }
}

我正在尝试比较两个对象,但我希望所有字符串都忽略大小写。不幸的是,以下内容无法编译:

// Does NOT allow me to call using ignore case
if (myObject1.Equals(myObject2, StringComparison.OrdinalIgnoreCase)) {
    Console.WriteLine("Match!");
}

有没有办法在不手动检查对象中的每个属性的情况下完成此操作?

4

2 回答 2

0

为了比较相等,你可以实现Equals,让我们在接口的帮助下做 IEquatable<MyObject>

public class MyObject : IEquatable<MyObject> {
  public string firstname { get; set; }
  public string lastname { get; set; }
  public int age { get; set; }
  public string occupation { get; set; }

  public bool Equals(MyObject other) {
    if (ReferenceEquals(this, other))
      return true;
    if (null == other)
      return false;

    return 
      string.Equals(firstname, other.firstname, StringComparison.OrdinalIgnoreCase) &&
      string.Equals(lastname, other.lastname, StringComparison.OrdinalIgnoreCase) &&
      string.Equals(occupation, other.occupation, StringComparison.OrdinalIgnoreCase) &&
      age == other.age;
  }

  public override bool Equals(object obj) => obj is MyObject other && Equals(other);

  public override int GetHashCode() =>
    (firstname?.GetHashCode(StringComparison.CurrentCultureIgnoreCase) ?? 0) ^
    (lastname?.GetHashCode(StringComparison.CurrentCultureIgnoreCase) ?? 0) ^
    (occupation?.GetHashCode(StringComparison.CurrentCultureIgnoreCase) ?? 0) ^
     age;
}

然后你可以使用定制的Equals

if (myObject1.Equals(myObject2)) {...}
于 2021-07-09T18:37:08.167 回答
0

您可以覆盖类的 Equals() 方法(这是每个对象都有的方法)。一切都在文档中得到了很好的描述。

public override bool Equals(Object obj)
   {
      //Check for null and compare run-time types.
      if ((obj == null) || ! this.GetType().Equals(obj.GetType()))
      {
         return false;
      }
      else {
         Point p = (Point) obj;
         return (x == p.x) && (y == p.y);
      }
   }
于 2021-07-09T18:02:46.337 回答