c# List.Contains() Method Returns False

后端 未结 9 1864
梦毁少年i
梦毁少年i 2021-01-28 06:04

In the code block below I would expect dictCars to contain: { Chevy:Camaro, Dodge:Charger }

But, dictCars comes back empty. Because this line returns false each time it

9条回答
  •  不思量自难忘°
    2021-01-28 06:46

    Your Car class is a reference type. By default reference types are compared to each other by reference, meaning they are considered the same if they reference the same instance in memory. In your case you want them to be considered equal if they contain the same values.

    To change the equality behavior, you need to override Equals and GetHashCode.

    If two cars are equal only when ID and Name are equal, the following is one possible implementation of the equality members:

    protected bool Equals(Car other)
    {
        return CarID == other.CarID && string.Equals(CarName, other.CarName);
    }
    
    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj))
            return false;
        if (ReferenceEquals(this, obj))
            return true;
        var other = obj as Car;
        return other != null && Equals(other);
    }
    
    public override int GetHashCode()
    {
        unchecked
        {
            return (CarID.GetHashCode() * 397) ^ 
                    (CarName != null ? CarName.GetHashCode() : 0);
        }
    }
    

    This implementation has been created automatically by ReSharper.
    It takes into account null values and the possibility of sub-classes of Car. Additionally, it provides a useful implementation of GetHashCode.

提交回复
热议问题