这更像是一个学术探究,而不是一个实际问题.是否有任何语言或框架功能可以或将来允许异构类型的dcitionary,例如
myDict.Add("Name", "Bill");
myDict.Add("Height", 1.2);
Run Code Online (Sandbox Code Playgroud)
myDict现在不包含两种object
类型的值,而是一个string
和一个double
?然后我可以找回我double
的
double dbl = myDict["Height"];
Run Code Online (Sandbox Code Playgroud)
并期望抛出一个双重或异常?
请注意:Name和Height值不一定是同一个对象.
如果您的自定义集合具有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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以定义你的键,如:
static readonly MyDictionaryKey<string> NameKey = new MyDictionaryKey<string>();
static readonly MyDictionaryKey<double> HeightKey = new MyDictionaryKey<double>();
Run Code Online (Sandbox Code Playgroud)
并使用它
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
Run Code Online (Sandbox Code Playgroud)