c# - Instantiate a random class on program start -
i'm having play around inheritance , few other concepts @ moment.
i have created console app amongst other things, holds following classes:
public abstract organism public abstract animal : organism public bird : animal public mammal : animal public reptile : animal public fish : animal public amphibian : animal public human : organism
when console app starts, want create new object either human, fish, mammal, reptile, bird or amphibian class. 1 of these classes instantiate randomly chosen.
once class has been randomly chosen, i've used console.writeline ask user key questions assign values given objects properties.
how create random object 1 of these classes?
// use dll of project running var runningassembly = assembly.getexecutingassemby(); // classes have "type" exposes information class var organismtype = typeof(organism); // keep track of organism classes we've found. var allorganismtypes = new list<type>(); // go through types in our project , locate inherit our // organism class foreach (var type in runningassembly.gettypes()) { if (organismtype.isassignablefrom(type)) allorganismtypes.add(type); } // find random index here (do yourself) var therandomindex = 10; var selectedtype = allorganismtypes[therandomindex]; // activator class in .net can create new objects // of type var selected = (organism)activator.createinstance(selectedtype);
there "mistakes" in code have correct yourself.
Comments
Post a Comment