C#:使用字符串字典,接口引用不同类
C#: Using a dictionary of string, interface to reference different classes
我想创建一个字典,它使用字符串作为键来实例化对象。这是我字典的开头:
Dictionary<string, ITerminalCommand> validInputs = new Dictionary<string, ITerminalCommand>()
{
{"help", TerminalCommandHelp},
{"exit", TerminalCommandExit},
};
这些终端命令 classes 实现了 ITerminalCommand 接口:
public class TerminalCommandHelp : MonoBehaviour, ITerminalCommand
{
//contents of class correctly implementing interface
}
问题是当我声明和初始化我的字典时,我收到一条错误消息
"TerminalCommandHelp" is a type, which is not valid in the given
context.
我认为可以抽象地使用接口来表示从它实现的任何 class?最终,当用户查找一个键时,我想创建那个特定 class 的实例。有人可以指出我的误解吗?谢谢!
//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()},
};
我想创建一个字典,它使用字符串作为键来实例化对象。这是我字典的开头:
Dictionary<string, ITerminalCommand> validInputs = new Dictionary<string, ITerminalCommand>()
{
{"help", TerminalCommandHelp},
{"exit", TerminalCommandExit},
};
这些终端命令 classes 实现了 ITerminalCommand 接口:
public class TerminalCommandHelp : MonoBehaviour, ITerminalCommand
{
//contents of class correctly implementing interface
}
问题是当我声明和初始化我的字典时,我收到一条错误消息
"TerminalCommandHelp" is a type, which is not valid in the given context.
我认为可以抽象地使用接口来表示从它实现的任何 class?最终,当用户查找一个键时,我想创建那个特定 class 的实例。有人可以指出我的误解吗?谢谢!
//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()},
};