【问题标题】:C#: Using a dictionary of string, interface to reference different classesC#:使用字符串字典,接口来引用不同的类
【发布时间】:2020-08-03 18:53:46
【问题描述】:

我想创建一个字典,它使用字符串作为键来实例化对象。这是我的字典的开头:

Dictionary<string, ITerminalCommand> validInputs = new Dictionary<string, ITerminalCommand>()
{
    {"help",  TerminalCommandHelp},
    {"exit",  TerminalCommandExit},
};

这些终端命令类实现了 ITerminalCommand 接口,如下所示:

public class TerminalCommandHelp : MonoBehaviour, ITerminalCommand
{
    //contents of class correctly implementing interface
}

问题是当我声明和初始化我的字典时,我收到一个错误提示

"TerminalCommandHelp" 是一个类型,在给定的情况下是无效的 上下文。

我认为可以抽象地使用接口来表示任何从中实现的类?最终,当用户查找密钥时,我想创建该特定类的实例。有人可以指出我的误解吗?谢谢!

【问题讨论】:

  • 您试图将类型传递给您的字典,而不是初始化对象。你需要一个 TerminalCommandHelp 和 TerminalCommandExit 的实例,而不是它们的名字。
  • I thought interfaces could be use abstractly to represent any class that implements from it 没错。但是您尝试使用的方式不正确。您需要将类的对象添加到字典中。不是班级本身。
  • 跟进其他正确的 cmets,您需要执行 new TerminalCommandHelp()new TerminalCommandExit()。演示小提琴在这里:dotnetfiddle.net/6TNeTR
  • 我明白了——那么有没有办法从这个字典中初始化一个类,比如:new validEntries["help"]()?还是我必须只传入一个初始化对象,并使用该初始化对象?我不能以这种方式创造更多?
  • 您正在创建一个包含ITerminalCommand 对象的字典,因此您需要正确构造您添加的每个对象。见Using Constructors (C# Programming Guide)。或者你真的想创建一个ITerminalCommand factories 的字典,就像Factory pattern, Avoid same switch case for different interface 中的那个?

标签: c# inheritance interface polymorphism implementation


【解决方案1】:
//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()},
    };

【讨论】:

    猜你喜欢
    • 2015-09-16
    • 2021-04-09
    • 1970-01-01
    • 2010-11-08
    • 2021-11-02
    • 1970-01-01
    • 2015-05-16
    • 2017-04-15
    • 1970-01-01
    相关资源
    最近更新 更多