讨论一下自定义类作为集合类键的必要条件。
SortedList的数据结构是链表,键值是排序后存储的。获取某个键值对应的值时,只需要比较操作。所以如果想将一个自定义类作为Key的话,必须要实现IComparable接口中的int CompareTo(object obj)方法。
例如
SortedList<SelfClass, string> list = new SortedList<SelfClass, string>(3);
list.Add(new SelfClass(1), "Apple");
list.Add(new SelfClass(2), "Orange");
list.Add(new SelfClass(3), "Pear");
MessageBox.Show(list[new SelfClass(2)]);
Dictionary的键都经过哈希后存储,每添加一个键值对,都会调用键对象中的GetHashCode方法,例如我定义了一个SelfClass,如下:
public class SelfClass : IComparable
{
public SelfClass(int i)
{
this.Index = i;
}
public int CompareTo(object obj)
{
if (obj.GetType() != this.GetType())
{
return -1;
}
SelfClass selfObj = obj as SelfClass;
int result = 0;
if (this.Index > selfObj.Index)
{
result = 1;
}
if (this.Index < selfObj.Index)
{
result = 1;
}
return result;
}
public override bool Equals(object obj)
{
if (obj.GetType() != this.GetType())
{
return false;
}
SelfClass other = obj as SelfClass;
if (this.Index != other.Index)
{
return false;
}
return true;
}
public int Index = 0;
public override string ToString()
{
return this.Index.ToString();
}
public override int GetHashCode()
{
return this.Index.ToString().GetHashCode();
}
}
那么利用上面的自定义类创建一个Dictionary<SelfClass, string>:
Dictionary<SelfClass, string> list = new Dictionary<SelfClass, string>(3);
list.Add(new SelfClass(1), "Apple");//调用GetHashCode方法
list.Add(new SelfClass(2), "Orange");//调用GetHashCode方法
list.Add(new SelfClass(3), "Pear");//调用GetHashCode方法
MessageBox.Show(list[new SelfClass(2)]);//调用GetHashCode方法,然后调用bool Equals(object obj)方法。
Hashtable同Dictionary的调用机制:
Hashtable ht = new Hashtable(3);
ht.Add(new SelfClass(1), "Apple");
ht.Add(new SelfClass(2), "Orange");
ht.Add(new SelfClass(3), "Pear");
MessageBox.Show(ht[new SelfClass(2)].ToString());
所以如果你的自定义类想要同时支持作为SortedList、Dictionary、Hashtable的键,请实现IComparable接口,请重写bool Equals(object obj)和override int GetHashCode()以及string ToString()方法,当然了toString方法不是必须的。
如果有疑惑的可以调试一下看看。