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(); } }