如果您有一个带有 Add 和 Get 方法的通用重载的自定义集合,那么您能够执行此操作的唯一方法是。但这意味着您在读取密钥时可能会要求错误的类型,因此与调用 Get 方法时自己进行强制转换相比,它不会给您带来太多(如果有的话)。
但是,如果您可以将泛型类型推入键中,那么就可以工作。类似的东西(此处未经测试的代码)
sealed class MyDictionaryKey<T>
{
}
class MyDictionary
{
private Dictionary<object, object> dictionary = new Dictionary<object, object>();
public void Add<T>(MyDictionaryKey<T> key, T value)
{
dictionary.Add(key, value);
}
public bool TryGetValue<T>(MyDictionaryKey<T> key, out T value)
{
object objValue;
if (dictionary.TryGetValue(key, out objValue))
{
value = (T)objValue;
return true;
}
value = default(T);
return false;
}
public T Get<T>(MyDictionaryKey<T> key)
{
T value;
if (!TryGetValue(key, out value))
throw new KeyNotFoundException();
return value;
}
}
然后你可以定义你的键,例如:
static readonly MyDictionaryKey<string> NameKey = new MyDictionaryKey<string>();
static readonly MyDictionaryKey<double> HeightKey = new MyDictionaryKey<double>();
并像这样使用它
var myDict = new MyDictionary();
myDict.Add(NameKey, "Bill"); // this will take a string
myDict.Add(HeightKey , 1.2); // this will take a double
string name = myDict.Get(NameKey); // will return a string
double height = myDict.Get(HeightKey); // will return a double