static void AsExemplo(List <Animal> animais) { foreach (var v in animais) { Gato g = v as Gato; if (g != null) { g.Miar(); } Cachorro c = v as Cachorro; if (c != null) { c.Latir(); } Rato r = v as Rato; if (r != null) { r.BarulhoDeRato(); } Elefante e = v as Elefante; if (e != null) { e.Barulho(); } } }
static void SimpleLinq(List <Animal> animais) { Rato r = (Rato)(from a in animais where a.Nome == "Jerry" select a).First(); r.BarulhoDeRato(); Gato g = (Gato)(from a in animais where a.Nome == "Gatito" select a).FirstOrDefault(); Console.WriteLine(g.Nome); Cachorro c = (Cachorro)(from a in animais where a.Nome == "Toto" select a).First(); c.Latir(); Elefante e = (Elefante)(from a in animais where a.Nome == "Pumba" select a).FirstOrDefault(); }
static void SimpleImplicityCast() { Animal gato = new Gato("Milk"); gato.Sexo = 'F'; Console.WriteLine(gato.ToString()); Animal cachorr = new Cachorro("Panthera"); cachorr.Sexo = 'F'; Console.WriteLine(cachorr.ToString()); Animal el = new Elefante("Dumbo"); el.Sexo = 'M'; Console.WriteLine(el.ToString()); Animal rato = new Rato("Jerry"); Console.WriteLine(rato.ToString()); }