C#:使用字符串字典,接口引用不同的类 [英] C#: Using a dictionary of string, interface to reference different classes
问题描述
我想创建一个字典,该字典使用字符串作为实例化对象的键.这是我字典的开头:
I would like to create a dictionary that uses strings as keys to instantiate objects. Here is the start of my dictionary:
Dictionary<string, ITerminalCommand> validInputs = new Dictionary<string, ITerminalCommand>()
{
{"help", TerminalCommandHelp},
{"exit", TerminalCommandExit},
};
这些终端命令类如下实现ITerminalCommand接口:
These terminal command classes implement the ITerminalCommand interface as such:
public class TerminalCommandHelp : MonoBehaviour, ITerminalCommand
{
//contents of class correctly implementing interface
}
问题在于,当我声明并初始化字典时,出现错误提示
"TerminalCommandHelp";是一种类型,在给定的条件下无效上下文.
"TerminalCommandHelp" is a type, which is not valid in the given context.
我认为接口可以抽象地用来表示从中实现的任何类吗?最终,当用户查找键时,我想创建该特定类的实例.有人可以指出我的误会吗?谢谢!
I thought interfaces could be use abstractly to represent any class that implements from it? Ultimately, when the user looks up a key, I want to create an instance of that particular class. Can someone point out my misunderstanding? Thank you!
推荐答案
//You are trying to pass their type not an instance.
Dictionary<string, ITerminalCommand> validInputs = new Dictionary<string, ITerminalCommand>()
{
{"help", TerminalCommandHelp},
{"exit", TerminalCommandExit},
};
//Initialize your types into objects and put those in your Dictionary.
IDictionary<string, ITerminalCommand> validInputs = new Dictionary<string, ITerminalCommand>()
{
{"help", new TerminalCommandHelp()},
{"exit", new TerminalCommandExit()},
};
这篇关于C#:使用字符串字典,接口引用不同的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!