Dictionary.ContainsKey return False, but a want True

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

    You need to override the Equals and GetHashCode methods of your Key class. In your case you could compare based on the key's name (or on any other unique property if your class is more complex).

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

提交回复
热议问题