static void Main(string[] args) { // Criar array para 10 animais Animal[] animals = new Animal[10]; // Criar instância de Random Random rnd = new Random(); // Colocar 10 animais aleatórios no array for (int i = 0; i < 10; i++) { int anim = rnd.Next(4); switch (anim) { case 0: animals[i] = new Bat(); break; case 1: animals[i] = new Bee(); break; case 2: animals[i] = new Cat(); break; case 3: animals[i] = new Dog(); break; } } // Para cada um dos animais... foreach (Animal animal in animals) { Console.WriteLine("------"); Console.WriteLine( $"{animal} makes {animal.Sound()}"); if (animal is IMammal) { Console.WriteLine("No of nipples: {0}", (animal as IMammal).NumberOfNipples); } if (animal is ICanFly) { Console.WriteLine("No of wings: {0}", (animal as ICanFly).NumberOfWings); } } }
private static void Main() { const int n = 10; Animal[] animals = new Animal[n]; Random rnd = new Random(); for (int i = 0; i < n; i++) { int r = rnd.Next(4); switch (r) { case 0: animals[i] = new Bat(); break; case 1: animals[i] = new Bee(); break; case 2: animals[i] = new Cat(); break; case 3: animals[i] = new Dog(); break; } } foreach (Animal a in animals) { Console.Write($"{a.GetType().Name} says "); Console.Write(a.Sound()); if (a is IMammal) { Console.Write( $", No.Nipples = {(a as IMammal).NumberOfNipples}"); } if (a is ICanFly) { Console.Write( $", No.Wings = {(a as ICanFly).NumberOfWings}"); } Console.WriteLine(); } }
static void Main(string[] args) { //Inicializar variáveis const int nAnimals = 10; Random rnd = new Random(); Animal[] animals = new Animal[nAnimals]; //Inicializar conteúdos array for (int i = 0; i < nAnimals; i++) { switch (rnd.Next(4)) { case 0: animals[i] = new Dog(); break; case 1: animals[i] = new Cat(); break; case 2: animals[i] = new Bat(); break; case 3: animals[i] = new Bee(); break; } } //Percorrer Array foreach (Animal a in animals) { Console.WriteLine($"\n\nThis animal is a {a}"); string nipples = a is IMammal ? "\nNum of nipples = " + (a as IMammal).NumberOfNipples : ""; string wings = a is ICanFly ? "\nNum of wings = " + (a as ICanFly).NumberOfWings : ""; Console.WriteLine("It makes " + a.Sound() + nipples + wings); } Console.ReadKey(); }
static void Main(string[] args) { //declarar variaveis const int n = 10; Animal[] animais = new Animal[n]; Random rnd = new Random(); //criar array 10 animais aleatorios for (int i = 0; i < n; i++) { switch (rnd.Next(2)) { case 0: animais[i] = new Bee(); break; case 1: animais[i] = new Bat(); break; } } //percorrer array de animais foreach (Animal a in animais) { //chamar metodo sound Console.Write(a.Sound() + " "); //se for mamifero apresentar n de nipples if (a is IMammal) { Console.Write($"Este animal tem" + (a as IMammal) + "mamilos"); } //se puder voar apresentar n de asas if (a is ICanFly) { Console.Write($"Este animal tem" + (a as ICanFly) + "asas"); } Console.WriteLine(); } }