我有以下延伸服务用于一些好的目的:
public static TV Put<TK, TV, TC>(this IDictionary<TK, TC> dictionary, TK key, TV value) where TC : ICollection<TV>, new()
{
TC collection = dictionary.TryGetValue(key);
if (collection == null)
{
dictionary.Add(key, collection = new TC());
}
collection.Add(value);
return value;
}
// Omit the following code, it is used within method Put
public static TV TryGetValue<TK, TV>(this IDictionary<TK, TV> dictionary, TK key)
{
TV result;
if (dictionary.TryGetValue(key, out result))
{
return result;
}
return default(TV);
}
我想另外将通用参数TC
约束为参考值,以便在TC为值类型时,用户在执行if (collection == null)
语句时不会遇到问题,那么如何当我希望集合都来自
TC : ICollection<TV>
和TC : class
答案 0 :(得分:4)
你可以试试这个:
public static TV Put<TK, TV, TC>(this IDictionary<TK, TC> dictionary, TK key, TV value)
where TC : class, ICollection<TV>, new()
{
...
}
此外,对于(值和参考)类型,您可以将条件if (collection == null)
替换为:
if (collection == default(TC))