首页 > 解决方案 > 如何创建类型声明的实例?

问题描述

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

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

class FooCommand : Command
{
}

class ListCommand : Command
{
}

现在我想要一个存储一些数据的结构和一个 Command 子类类 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
});

...

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

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

标签: c#typesinstance

解决方案


你必须用以下包装类型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");

推荐阅读