【问题标题】:Object comparison but ignore case of strings对象比较但忽略字符串的大小写
【发布时间】:2021-07-09 17:39:38
【问题描述】:

我有一个像这样的对象:

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!");
}

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

【问题讨论】:

  • 写你自己的.Equals覆盖
  • 这能回答你的问题吗? Comparing object properties in c#,特别是this 的答案,涉及覆盖@Charlieface 提到的.Equals
  • 获得“免费”值比较的唯一方法是使用新的record type,但即便如此,您也必须覆盖它以忽略大小写。

标签: c# object comparison ignore-case


【解决方案1】:

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

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);
      }
   }

【讨论】:

    【解决方案2】:

    为了比较相等,你可以实现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)) {...}
    

    【讨论】:

      猜你喜欢
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      • 2011-10-06
      • 2011-02-20
      相关资源
      最近更新 更多