c# Dictionary 自定义类型的key 如何判断是否存在 财富值68

2016-10-18 14:06发布

public class DicConfigKey     {         public string ID { get; set; }         public string TypeID { get; set; }     }
Dictionary<DicConfigKey, string> dic = new Dictionary<DicConfigKey, string>();             dic.Add(new DicConfigKey { ID = "1", TypeID = "010" }, "test1");             dic.Add(new DicConfigKey { ID = "1", TypeID = "020" }, "test2");             dic.Add(new DicConfigKey { ID = "2", TypeID = "020" }, "test3");             DicConfigKey key = new DicConfigKey() { ID = "2", TypeID = "020" };             //bool flag = dic.Keys.Contains(key);             bool flag = dic.ContainsKey(key);

如上代码,Dictionary中自定义类型的键Key,如何判断key是否存在呢,dic.Keys.Contains和dic.ContainsKey都返回false


问题已解决,重写DicConfigKey的Equals和GetHashCode方法即可,代码如下

public class DicConfigKey     {         public string ID { get; set; }         public string TypeID { get; set; }          public override bool Equals(object obj)         {             if (obj == this)                 return true;             if (!(obj is DicConfigKey))                 return false;             var dicconfikey = (DicConfigKey)obj;             return ID == dicconfikey.ID && TypeID == dicconfikey.TypeID;         }          public override int GetHashCode()         {             return (ID + TypeID).GetHashCode();         }     }
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
3条回答

换struct

一周热门 更多>