2012年10月25日 星期四

{C#} Dictionary Custom Key is class

如 Dictionary的key 值是客製,從class而來
如要讓Dictionary裡的key不重覆,需覆寫GetHashCode()與Equals(object obj)
Dictionary.ContainsKey() 才會有效果

EX:
Dictionary<ErrorData, string> dicTemp = new Dictionary<ErrorData, string>();
ErrorData er=new ErrorData();
er.CUR="abc";
er.Name="Jake";
if (!dicTemp.ContainsKey(er))
    dicTemp.Add(er,"good");


建立類別
  public class ErrorData
    {
        public string CUR{ set; get; }

        public string Name{ set; get; }

        public override int GetHashCode()
        {
            //return base.GetHashCode();
            return Name.GetHashCode() ^ CUR.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            ErrorData v1 = obj as ErrorData;
            return v1.PN == PN && v1.Currency == Currency;
        }
       
    }


參考資料:
http://www.cnblogs.com/pmars/archive/2012/03/02/2376610.html