如何用class在Dictionary里面作为Key使用

View Code
        public class value
{
public int key1;
public int key2;
public int data;
}
public struct key
{
public int key1;
public int key2;
public static implicit operator key(value value) { return new key { key1 = value.key1, key2 = value.key2 }; }
}



public static void Test()
{

Dictionary<key, int> dic = new Dictionary<key, int>();
dic[new value { key1 = 1, key2 = 2, data = 3 }] = 3;
Console.WriteLine(dic.ContainsKey(new value { key1 = 1, key2 = 2, data = 4 }));

}

这个是一个例子,其中结构体key作为Dictionary的Key来使用,里面有key1,key2来标识Value的不同,这个就可以动态的去重写class 的Equals方法,但是如果在其他地方也需要用到Value这个类的话,并且定义的Equals如果不同,就得重写一个key结构体来代替Value的Equals方法!

当然,这个还可以用继承的方式来重写Value的Equals方法!

View Code
        public class value
{
public int key1;
public int key2;
public int data;
}

public class value1 : value
{
public override int GetHashCode()
{
return base.GetHashCode();
}

public override bool Equals(object obj)
{
value1 v1 = obj as value1;
return v1.key1 == key1 && v1.key2 == key2;
}
}

这个应该就是通用的表示方法了!

posted @ 2012-03-02 09:39  pmars  阅读(897)  评论(0编辑  收藏  举报