嚴格按照你的例子(即一類只能有一個條目)就可以實現這個雙向的:
自定義詞典
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;
}
}
第一種方法更明確,因爲另一種方法只需要特定ic類型的字典。
這很好。無論如何,我可以得到像這樣的東西來處理它呢? properties.Add(someVar); –