Come fare una classe generica con l'ereditarietà?
-
23-08-2019 - |
Domanda
Come posso fare il seguente lavoro codice? Non credo che io capisco C # generici. Forse, qualcuno mi può puntare nella giusta direzione.
public abstract class A
{
}
public class B : A
{
}
public class C : A
{
}
public static List<C> GetCList()
{
return new List<C>();
}
static void Main(string[] args)
{
List<A> listA = new List<A>();
listA.Add(new B());
listA.Add(new C());
// Compiler cannot implicitly convert
List<A> listB = new List<B>();
// Compiler cannot implicitly convert
List<A> listC = GetCList();
// However, copying each element is fine
// It has something to do with generics (I think)
List<B> listD = new List<B>();
foreach (B b in listD)
{
listB.Add(b);
}
}
E 'probabilmente una risposta semplice.
Aggiornamento: In primo luogo, questo non è possibile in C # 3.0, ma sarà possibile in 4,0 C #.
Per farlo funzionare in C # 3.0, che è solo una soluzione temporanea fino a 4.0, utilizzare il seguente:
// Compiler is happy
List<A> listB = new List<B>().OfType<A>().ToList();
// Compiler is happy
List<A> listC = GetCList().OfType<A>().ToList();
Soluzione
si può sempre fare questo
List<A> testme = new List<B>().OfType<A>().ToList();
"Bojan Resnik", ha sottolineato, si potrebbe anche fare ...
List<A> testme = new List<B>().Cast<A>().ToList();
Una differenza da notare è che Fusioni
Altri suggerimenti
La ragione per cui questo non funziona è perché non può essere determinato per essere sicuri. Si supponga di avere
List<Giraffe> giraffes = new List<Giraffe>();
List<Animal> animals = giraffes; // suppose this were legal.
// animals is now a reference to a list of giraffes,
// but the type system doesn't know that.
// You can put a turtle into a list of animals...
animals.Add(new Turtle());
E hey, basta mettere una tartaruga in un elenco di giraffe, e l'integrità del sistema tipo è ora violata. Ecco perché questo è illegale.
La chiave qui è che "animali" e "giraffe" si riferiscono allo stesso oggetto, e che oggetto è una lista di giraffe. Ma l'elenco delle giraffe non può fare tanto quanto un elenco di animali possono fare; in particolare, non può contenere una tartaruga.