简体   繁体   English

从字符串实例化继承的类

[英]Instantiating an Inherited class from a string

I'm wondering if there is an easy way to instantiate an inherited object (knowing the class name). 我想知道是否有一种简单的方法来实例化继承的对象(知道类名)。

Assuming I have 假设我有

public abstract Monster{
    public string name;
    public string specie;
    public Stats baseStats;
    public string imgDir;
}

and

public Specie1 : Monster{
    public new string specie = "Specie1";
    public new Stats baseStats = {1,2,3,4,5};
    public new imgDir = "dir/specie1.png";
    public Specie1(string n){
        name = n;
    }
}

My objective is to load from saved file the monsters, testing it with only one specie, I do the following: 我的目标是从保存的文件中加载怪物,仅用一个物种对其进行测试,我执行以下操作:

Monster[0] = new Specie1("foo");

But in the event that I have many species, is there a way to instantiate generically? 但是,如果我有很多种类,是否可以通用地实例化?

For example: 例如:

string specie = loadSpecie();
Monster[] = new specie("foo");

I am hoping there is a way to do this without creating a lot of switches and ifs everywhere. 我希望有一种方法可以在不创建大量开关和ifs的情况下执行此操作。

I was thinking of creating a constructor 我在想创建一个构造函数

Monster(string species,string name){
    if(species == "Specie1"){
        return new Specie1(name);
    }
}

But I think that would be horrible programming, and not scalable at all. 但是我认为这将是可怕的编程,而且根本无法扩展。

You can use a factory method to instance the monster sub-classes. 您可以使用工厂方法来实例化怪物子类。

public abstract Monster
{
    public string name;
    public string specie;
    public Stats baseStats;
    public string imgDir;

    public static Monster CreateMonster(string monster)
    {
        Type[] types = GetTypeInfo().Assembly.GetTypes();
        Type monsterType = types.FirstOrDefault(t => t.Name.ToLower().Equals(monster.ToLower()));

        if (monsterType == null)
            throw new InvalidOperationException("The given monster does not have a Type associated with it.");

        return Activator.CreateInstance(monsterType) as Monster;
    }
}

public class Cat : Monster
{
}

The CreateMonster method looks up all of the types in the current assembly and creates an instance of the first Type it finds that has a name that matches the monster name provided. CreateMonster方法查找当前程序集中的所有类型,并创建其找到的第一个Type的实例,该实例的名称与提供的怪物名称匹配。 You would probably want to include some logic so that it doesn't try to instance an abstract class, and ensure the type is actually a child class of Monster. 您可能希望包括一些逻辑,以便它不尝试实例化抽象类,并确保该类型实际上是Monster.的子类Monster.

Personally I would probably decorate the monster sub-classes with an attribute that gives a friendly name to each class. 我个人可能会用给每个类起友好名称的属性来装饰怪物子类。 I would save the attribute value to the file, and to the first Type that has an attribute matching the monster name. 我会将属性值保存到文件中,并保存到第一个具有与怪物名称匹配的属性的Type。 I would also only do the GetTypes() call once. 我也只会做一次GetTypes()调用。 You should cache the result in a private static field in the Monster class. 您应该将结果缓存在Monster类的私有静态字段中。 This way, you only use reflection once. 这样,您只需使用一次反射。 In any event, the above code works and can be used like this: 无论如何,上面的代码都可以工作,并且可以像这样使用:

Monster cat = Monster.CreateMonster("Cat");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM