Dictionary.ContainsKey return False, but a want True

前端 未结 12 944
野性不改
野性不改 2020-12-03 10:16
namespace Dic
{
public class Key
{
    string name;
    public Key(string n) { name = n; }
}

class Program
{
    static string Test()
    {
        Key a = new Key(         


        
12条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 11:19

    1. Override Equals, Get Hash Code, and the '==' Operator.

    The Key class must override Equals in order for the Dictionary to detect if they are the same. The default implementation is going to check references only.

    Here:

            public bool Equals(Key other)
            {
                return this == other;
            }
    
            public override bool Equals(object obj)
            {
                if (obj == null || !(obj is Key))
                {
                    return false;
                }
    
                return this.Equals((Key)obj);
            }
    
            public static bool operator ==(Key k1, Key k2)
            {
                if (object.ReferenceEquals(k1, k2))
                {
                    return true;
                }
    
                if ((object)k1 == null || (object)k2 == null)
                {
                    return false;
                }
    
                return k1.name == k2.name;
            }
    
            public static bool operator !=(Key k1, Key k2)
            {
                if (object.ReferenceEquals(k1, k2))
                {
                    return false;
                }
    
                if ((object)k1 == null || (object)k2 == null)
                {
                    return true;
                }
    
                return k1.name != k2.name;
            }
    
            public override int GetHashCode()
            {
                return this.name == null ? 0 : this.name.GetHashCode();
            }
    

    2. If Possible, use a struct.

    You should use a struct for immutable datatypes like this, since they are passed by value. This would mean that you coulnd't accidentally munge two different values into the same key.

提交回复
热议问题