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(); } }
付费偷看金额在0.1-10元之间
http://stackoverflow.com/ques...
或者使用GetHashCode/Equals自己来写对比规则
换struct
一周热门 更多>