如何创建类型声明的实例?

时间:2019-02-24 03:49:16

标签: c# types instance

我想将一个类声明存储在一个结构中,然后实例化该类中的新对象,但是我遇到了一些障碍。我知道如何使用其他几种语言来完成此操作,但是在C#中,我还没有获得任何成功。

abstract class Command
{
    // Base class for all concrete command classes.
}

class FooCommand : Command
{
}

class ListCommand : Command
{
}

现在,我想要一个存储一些数据的结构和一个Command子类参考:

struct CommandVO
{
    string trigger;
    string category;
    Type commandClass;
}

稍后在其他地方,我想从字典中获取VO结构并创建具体的命令对象:

var commandMap = new Dictionary<string, CommandVO?>(100);
commandMap.Add("foo", new CommandVO
{
    trigger = "foo", category = "foo commands", commandClass = FooCommand
});
commandMap.Add("list", new CommandVO
{
    trigger = "list", category = "list commands", commandClass = ListCommand
});

...

var commandVO = commandMap["foo"];
if (commandVO != null)
{
    var commandClass = commandVO.Value.commandClass;
    // How to instantiate the commandClass to a FooCommand object here?
}

我已经在page中检查了有关如何实例化类型的方法,但是由于Type不代表任何具体的类,我想知道如何让commandClass实例化为适当的类型其类型的对象?在这种情况下将类声明存储为Type是否正确,还是有更好的方法?

1 个答案:

答案 0 :(得分:1)

您必须用typeof()包装类型:

var commandMap = new Dictionary<string, CommandVO?>(100);
commandMap.Add("foo", new CommandVO {
    trigger = "foo", category = "foo commands", commandClass = typeof(FooCommand)
});

您可以这样编写扩展方法:

internal static class CommandHelper {

    internal static Command createCommand(this Dictionary<string, CommandVO?> d, string name) {
        if (!d.ContainsKey(name)) return null;
        return Activator.CreateInstance(d[name]?.commandClass) as Command;
    }

}

比您可以获得Cammand实例:

var instance = commandMap.createCommand("foo");