Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

c# - Instantiate a random class on program start

I'm just having a play around with inheritance and a few other concepts at the moment.

I have created a console app that amongst other things, holds the 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 the console app starts, I want to create a new object from either the Human, Fish, Mammal, Reptile, Bird or Amphibian class. Which one of these classes to instantiate is to be randomly chosen.

Once a class has been randomly chosen, I've used console.writeline to ask the user key questions to assign values to the given objects properties.

How do I create a random object from one of these classes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
// use the DLL of the project which is currently running
var runningAssembly = Assembly.GetExecutingAssemby();

// all classes have a "Type" which exposes information about the class
var organismType = typeof(Organism);

// to keep track of all organism classes that we've found.
var allOrganismTypes = new List<Type>();

// go through all types in our project and locate those who inherit our 
// organism class
foreach (var type in runningAssembly.GetTypes())
{
    if (organismType.IsAssignableFrom(type))
        allOrganismTypes.Add(type);
}

// Find a random index here (do it yourself)
var theRandomIndex = 10;


var selectedType = allOrganismTypes[theRandomIndex];

// activator is a class in .NET which can create new objects 
// with the help of a type
var selected = (Organism)Activator.CreateInstance(selectedType);

There are some "mistakes" in the code that you have to correct yourself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...