代码之家  ›  专栏  ›  技术社区  ›  VoodooChild

list.contains未按预期工作

  •  4
  • VoodooChild  · 技术社区  · 14 年前

    如果我有一个类型的对象 MyBull 和A List<MyBull> orig :

    // Just an example
    MyBull x = getMeTheObjectWithIdFromDB(9);
    
    orig.add(x);
    
    // Again same? data object
    MyBull y = getMeTheObjectWithIdFromDB(9);
    

    为什么这是假的?

    // This is false, even though all the properties
    // of x and y are the same.
    orig.Contains<MyBull>(y); 
    
    4 回复  |  直到 10 年前
        1
  •  23
  •   Samuel Neff    14 年前

    默认情况下,对象将公开基于引用的相等。如果需要自定义规则(如基于ID字段的相等性),则需要重写 Equals GetHashCode 方法。

        2
  •  8
  •   Jonas Elfström    10 年前

    如果你可以使用LINQ,那么你可以

    class Vessel
    {
        public int id { get; set; }
        public string name { get; set; }
    }
    

    var vessels = new List<Vessel>() { new Vessel() { id = 4711, name = "Millennium Falcon" } };
    
    var ship = new Vessel { id = 4711, name = "Millencolin" };
    
    if (vessels.Any(vessel => vessel.id == ship.id))
        Console.Write("There can be only one!");
    
        3
  •  4
  •   casperOne    14 年前

    这是因为mybull实例正在通过引用进行比较。从.NET的角度来看,x和y都是 不同的实例 因此不平等。

    为了避开这个,你必须 override the Equals and GetHashCode methods (这意味着您可能应该实现 IEquatable<MyBull> 重写==和!=操作员)。

        4
  •  3
  •   David Fox    14 年前

    你的mybull对象实现了吗 IEquatable<T>.Equals ?此方法将确定两个对象的相等性

    OP请求

    您的MyBull类将实现IEquatable

    public class MyBull : IEquatable<MyBull>
    

    然后你需要覆盖 Equals 方法

    public bool Equals(MyBull theOtherMyBull)
    

    正如大卫尼尔在下面提到的,当您比较同一类型的对象时,这是最好的使用方法——您就是这样。重写Object.Equals和Object.GetHashCode也将起作用。