I have a problem, which I can not explain in simple words, so I used to use an examination lipel that I will use the Istalets in my mind.
I have three class cows, horses and sheep. And class animals and now I want to clothe animals to store animal list but only one specific species (select user manufacturer selector type). Now I do not want to use templates and I do not want to create three separate lists in one class. So I wonder what is the other way to do this. I think this can be done:
public class cattle {} public square cow: animal {} public class horse: animal {} public square sheep: animal {} public class animal { Public string type {get; Protected Set; } Public List & gt; Animals & gt; List {get; Set;} public animal (string type) {this.Type = type; Switch (type) {case "cow": list = new list & lt; Cows & gt; (); break; Case "Horses": List = New List & lt; Horses & gt; (); break; Case "sheep": list = new list & lt; Sheep & gt; (); break; }}}
Of course this code is only a sample and it does not work, but I think I have a problem solved. I believe that I have seen something like this in the past But I do not know whether it was C # or Java. And if I miss it, then something like this looks:
animal animal = new cow ();
Tell me what is the way to do this.
I believe that generic is the best way to solve your problem, the way I hope That this code will help you
using the system; Using System.Collections; Using System.Collections.Generic; Using System.Linq; Using System.Text; System usage threading. Task; Namespace Console Application 7 {Public Square Animals} Public Squares Cow: Animals {} Public Squares Horses: Animals {} Public Squares Sheep: Animals {} Public Squares Animals {Safe ArrayList List {get; Set; } Safe Type Type {get; Set; } Public animal (type type) {this.Type = type; This.list = new Arrayist (); } Public Zero AddAnimal (Animal Animals) {If (animal.GetType () == this.Type) Add this .list. (Animal); And throw new exceptions ("expected type"); }} Class program {static zero main (string [] arg) {var s1 = new sheep}; Var s2 = new sheep (); Var C1 = new cow (); Var sheepList = new animal (typef (sheep)); SheepList.AddAnimal (S1); SheepList.AddAnimal (s2); SheepList.AddAnimal (c1); // throws an exception}}}
No comments:
Post a Comment