Dictionary.ContainsKey return False, but a want True

前端 未结 12 1005
野性不改
野性不改 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:08

    Then you will need to override GetHashCode and Equals on the Key class.

    Without doing that, you get the default implementation of both. Which results in the hashcode for a and b to be most likely not the same (I don't know how what the default implementation looks like), and a to be definitely not equal to b (the default Equals() implementation checks reference equality).

    In your case, assuming "name" is not a null, it could be implemented as

       public class Key
       {
            string name;
            public override int GetHashCode()
            {
                 return name.GetHashCode();
            }
    
            public override bool Equals(object obj)
            {
                if (obj == null)
                {
                  return false;
                }
    
                Key objAsKey = obj as Key;
                if (objAsKey == null)
                {
                  return false;
                }
    
                return this.name.Equals(objAsKey.Name);
            }
        }
    

    Whether this is a satisfactory hash is a different story, but it shows the principle, nevertheless.

提交回复
热议问题