在程序启动时实例化一个随机类 [英] Instantiate a random class on program start

查看:156
本文介绍了在程序启动时实例化一个随机类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

当控制台应用程序启动时,我想从Human,Fish,Mammal,Reptile,Bird或Amphibian类创建一个新对象。要实例化这些类中的哪一个是随机选择的。

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.

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

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?

推荐答案

// 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.

这篇关于在程序启动时实例化一个随机类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆