Problema al obtener el método de extensión genérica para que funcione correctamente
-
21-09-2019 - |
Pregunta
Estoy intentando crear el AddRange método de extensión de HashSet para que pueda hacer algo como esto:
var list = new List<Item>{ new Item(), new Item(), new Item() };
var hashset = new HashSet<Item>();
hashset.AddRange(list);
Esto es lo que tengo hasta ahora:
public static void AddRange<T>(this ICollection<T> collection, List<T> list)
{
foreach (var item in list)
{
collection.Add(item);
}
}
El problema es que cuando intento utilizar AddRange, estoy recibiendo este error del compilador:
The type arguments for method 'AddRange<T>(System.Collections.Generic.ICollection<T>, System.Collections.Generic.List<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
En otras palabras, tengo que terminar con esto en su lugar:
hashset.AddRange<Item>(list);
¿Qué estoy haciendo mal aquí?
Solución
Su código funciona bien para mí:
using System.Collections.Generic;
static class Extensions
{
public static void AddRange<T>(this ICollection<T> collection, List<T> list)
{
foreach (var item in list)
{
collection.Add(item);
}
}
}
class Item {}
class Test
{
static void Main()
{
var list = new List<Item>{ new Item(), new Item(), new Item() };
var hashset = new HashSet<Item>();
hashset.AddRange(list);
}
}
Podría darle un corto similar pero completo programa que falla al compilar?
Otros consejos
Uso
hashSet.UnionWith<Item>(list);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow