严格根据您的示例(即一种类型只能有一个条目),您可以通过两种方式实现:
自定义词典
public class TypedDictionary : Dictionary<Type, object>
{
public void Add<T>(T value)
{
var type = typeof (T);
if (ContainsKey(type))
this[type] = value;
else
Add(type, value);
}
public T Get<T>()
{
// Will throw KeyNotFoundException
return (T) this[typeof (T)];
}
public bool TryGetValue<T>(out T value)
{
var type = typeof (T);
object intermediateResult;
if (TryGetValue(type, out intermediateResult))
{
value = (T) intermediateResult;
return true;
}
value = default(T);
return false;
}
}
扩展方法
public static class TypedDictionaryExtension
{
public static void Add<T>(this Dictionary<Type, object> dictionary, T value)
{
var type = typeof (T);
if (dictionary.ContainsKey(type))
dictionary[type] = value;
else
dictionary.Add(type, value);
}
public static T Get<T>(this Dictionary<Type, object> dictionary)
{
// Will throw KeyNotFoundException
return (T) dictionary[typeof (T)];
}
public static bool TryGetValue<T>(this Dictionary<Type, object> dictionary, out T value)
{
var type = typeof (T);
object intermediateResult;
if (dictionary.TryGetValue(type, out intermediateResult))
{
value = (T) intermediateResult;
return true;
}
value = default(T);
return false;
}
}
第一种方法更明确,因为另一种方法只需要特定类型的字典。