Dictionary.ContainsKey return False, but a want True

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

    In order to use your own classes as dictionary keys, you should override GetHashCode and Equals. Otherwise it will use the memory address to check for equality.

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

提交回复
热议问题