在程序启动时实例化一个随机类

Stu*_*86C 1 c# oop inheritance console-application

我现在正忙着继承和其他一些概念.

我创建了一个控制台应用程序,其中包含以下类:

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
Run Code Online (Sandbox Code Playgroud)

当控制台应用程序启动时,我想从人类,鱼类,哺乳动物,爬行动物,鸟类或两栖动物类创建一个新对象.要实例化这些类中的哪一个是随机选择的.

一旦随机选择了一个类,我就使用console.writeline来询问用户关键问题,以便为给定的对象属性赋值.

如何从这些类之一创建随机对象?

jga*_*fin 5

// 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);
Run Code Online (Sandbox Code Playgroud)

代码中有一些"错误",你必须纠正自己.