C# 一个泛型类型的多个where约束
我有以下一段扩展,有一些很好的用途:C# 一个泛型类型的多个where约束,c#,.net,generics,C#,.net,Generics,我有以下一段扩展,有一些很好的用途: 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) {
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和TC:class您可以尝试以下方法:
public static TV Put<TK, TV, TC>(this IDictionary<TK, TC> dictionary, TK key, TV value)
where TC : class, ICollection<TV>, new()
{
...
}
if (collection == default(TC))