retrieve value from hashtable with clone of key; C#
I would like to know if there is any possible way to retrieve an item from a hashtable using a key that is identical to the actual key, but a different object. I understand why it is probably not possible, but I would like to see if there is any tricky way to do it.
My problem arises from the fact that, being as stupid as I am, I created hashtables with int[] as the keys, with the integer arrays containing indices representing spatial position. I somehow knew that I needed to create a new int[] every time I wanted to add a new entry, but neglected to think that when I generated spatial coordinate arrays later they would be worthless in retrieving the values from my hashtables.
Now I am trying to decide whether to rearrange things so that I can store my values in ArrayLists, or whether to search through the list of keys in the Hashtable for the one I need every time I want to get a value, neither of the options being very cool.
Unless of course there is a way to get //1 to work like //2!
Thanks in advance.
static void Main(string[] args)
{
Hashtable dog = new Hashtable();
//1
int[] man = new int[] { 5 };
dog.Add(man, "hello");
int[] cat = new int[] { 5 };
Console.WriteLine(dog.ContainsKey(cat)); //false
//2
int boy = 5;
dog.Add(boy, "wtf");
开发者_运维技巧 int kitten = 5;
Console.WriteLine(dog.ContainsKey(kitten)); //true;
}
Yes, you have two options.
Implement
Equals()
andGetHashCode()
in the key classes.Create a custom
IEqualityComparer
and pass it to theHashtable
constructor.
You'll want to implement Equals()
and GetHashCode()
yourself when the implementations make sense for all usages of your custom class. If they are only appropriate sometimes, then use a custom IEqualityComparer
which has the same functionality but provides it separate from the class itself. This second option also allows you to provide custom rules for non-custom key classes.
精彩评论