我现在正忙着继承和其他一些概念。
我创建了一个控制台应用程序,其中包含以下类:
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类创建一个新对象。要实例化这些类中的哪一个是随机选择的。
一旦随机选择了一个类,我就使用console.writeline向用户询问关键问题,以便为给定的对象属性赋值。
如何从其中一个类创建随机对象?
答案 0 :(得分: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);
代码中有一些“错误”,你必须纠正自己。
答案 1 :(得分:1)
如果您需要从列表中选择类型,您可以:
Type[] animals = new Type[]{ typeof(Bird), typeof(Mammal), typeof(Reptile), typeof(Fish), typeof(Amphibian) };
Animal animal = animals[new Random().Next(animals.Length)].GetConstructor(new Type[]{}).Invoke(new object[]{}) as Animal;
但是如果你重视代码中的简单性/可读性(并且你应该),那么如果可能的话,以下内容会更好:
Animal animal = null;
switch (new Random().Next(5))
{
case 0:
animal = new Bird();
break;
case 1:
animal = new Mammal();
...
}
编辑:我忘记了Activator.CreateInstance(比我建议的代码简单),但是如果没有很多类,使用更基本的代码会更具可读性,并且允许更多的灵活性(你不需要每种类型)有一个偶然的概率。)
答案 2 :(得分:0)
不使用Reflection,您可以使用类实例列表来实现它:
var classlist = new List<Organism>();
classlist.Add(new Bird());
classlist.Add(new Mammal());
classlist.Add(new Reptile());
classlist.Add(new Fish());
classlist.Add(new Amphibian());
classlist.Add(new Human());
var r = new Random();
var instance = classlist[r.Next(0,5)];