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

C# 如何创建类型声明的实例?,c#,types,instance,C#,Types,Instance,我想在结构中存储一个类声明,然后从该类实例化新对象,但我遇到了一些障碍。我知道用其他几种语言如何做到这一点,但在C语言中我还没有取得任何成功 abstract class Command { // Base class for all concrete command classes. } class FooCommand : Command { } class ListCommand : Command { } 现在我想要一个存储一些数据的结构和一个命令子类class ref:

我想在结构中存储一个类声明,然后从该类实例化新对象,但我遇到了一些障碍。我知道用其他几种语言如何做到这一点,但在C语言中我还没有取得任何成功

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

class FooCommand : Command
{
}

class ListCommand : Command
{
}
现在我想要一个存储一些数据的结构和一个命令子类class ref:

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
});

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

您必须使用typeof包装类型:


使用Activator.CreateInstance这是否可以编译给您?你必须写作typeofFooCommand@PawełAudionysos这部分是我头脑中编写的伪代码。我想我找到了我需要的:var instance=Activator.CreateInstancecommandClass;var obj=作为命令的实例;如果obj!=null var命令=obj;添加它作为一个答案:不是每一个偶然发现这一点的人都会阅读评论。在这里使用Func而不是Type是很常见的。这避免了Activator.CreateInstance的开销,还允许您使用没有无参数构造函数的命令。Func-Factory-then-Factory==>new-FooCommand来分配它,以及.Factory来调用它并创建你的新命令感谢关于使用typeof的提示!
var commandVO = commandMap["foo"];
if (commandVO != null)
{
    var commandClass = commandVO.Value.commandClass;
    // How to instantiate the commandClass to a FooCommand object here?
}
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;
    }

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