任务是将具有不同类型钥匙的物体列入字典,但标准字典由同类钥匙界定。
你们可能有不同的钥匙界定自己的物体,这些钥匙需要放在一个字典上,因此钥匙可以不同类型。
最简单的方式是,对关键目标进行接口,然后这些物体可以相同(通用接口类型)。
守则实例显示了两个具有共同接口的关键结构,以及该接口的字典工程(伊凯)。
值得记住的是,词典要求(至少)实施一个关键的“平等”和“发展”;接口,以及关键功能的实施——字典的业绩取决于这一点。
public interface IKey : System.IEquatable<IKey>
{
}
public struct Key1 : IKey
{
public int Value;
public Key1(int value)
{
Value = value;
}
public override int GetHashCode()
{
// !! return adequate hashcode
return Value.GetHashCode();
}
public bool Equals(IKey other)
{
// !! return adequate equals
return Value.Equals(((Key1)other).Value);
}
public override string ToString()
{
return Value.ToString();
}
}
public struct Key2 : IKey
{
public string Value;
public Key2(string value)
{
Value = value;
}
public override int GetHashCode()
{
// !! return adequate hashcode
return Value.GetHashCode();
}
public bool Equals(IKey other)
{
// !! return adequate equals
return Value.Equals(((Key2)other).Value,
System.StringComparison.Ordinal);
}
public override string ToString()
{
return Value;
}
}
public class DictionaryIKey<TValue> :
System.Collections.Generic.Dictionary<IKey, TValue>
{
public void Add(int key, TValue value)
{
Add(new Key1(key), value);
}
public void Add(string key, TValue value)
{
Add(new Key2(key), value);
}
public bool TryGetValue(int key, out TValue value)
{
return TryGetValue(new Key1(key), out value);
}
public bool TryGetValue(string key, out TValue value)
{
return TryGetValue(new Key2(key), out value);
}
}
public static void Run()
{
DictionaryIKey<string> dict = new DictionaryIKey<string>(3);
string value = "123456, John, Duus";
// add object to dictionary, and this object is accessible
// by keys of different types
dict.Add(123456, value);
dict.Add("John", value);
dict.Add("Duus", value);
string _out;
dict.TryGetValue(123456, out _out);
System.Console.WriteLine(_out);
dict.TryGetValue("John", out _out);
System.Console.WriteLine(_out);
dict.TryGetValue("Duus", out _out);
System.Console.WriteLine(_out);
dict.TryGetValue(111000, out _out);
System.Console.WriteLine(_out);
dict.TryGetValue("no??", out _out);
System.Console.WriteLine(_out);
// output:
// 123456, John, Duus
// 123456, John, Duus
// 123456, John, Duus
// <empty>
// <empty>
}