实例化字典中的泛型类型



我有几个实现ITerminalCommand接口的类:

public class TerminalCommandHelp : MonoBehaviour, ITerminalCommand { //... }
public class TerminalCommandExit : MonoBehaviour, ITerminalCommand { //... }

在另一个类中,我希望能够在字典中查找字符串并创建ITerminalCommand的新实例,但我不知道该如何做到这一点,所以在下面我写了一些伪代码,希望有人能理解我要做什么。

Dictionary<string, ITerminalCommand> validInputs = new Dictionary<string, ITerminalCommand>()
{
{
"help", 
//Some reference to the TerminalCommandHelp class so I can instantiate it at my own will
},
{   
"exit",
//Some reference to the TerminalCommandExit class so I can instantiate it at my own will
}
};
//Create a new object based on the key I am looking up, and supply some arguments to the constructor
ITerminalCommand genericTerminalCommand = new validInputs["help"](arguments);
//Run a method on the newly instantiated object
genericTerminalCommand.Execute();

如何"抽象地"引用字典中的类类型,以便实例化它并为它提供一些参数

试试这个代码:

Dictionary<string, Type> validInputs = new Dictionary<string, Type>()
{
{ "help", typeof(TerminalCommandHelp) },
{ "exit", typeof(TerminalCommandExit) },
};
ITerminalCommand genericTerminalCommand = (ITerminalCommand)Activator.CreateInstance(validInputs["help"]);

最新更新