c# - 创建字典<string, class>

标签 c# .net dictionary

在带有 Unity 的 C# 中,我正在尝试创建类字典。

所有类都继承自具有许多虚拟方法的基类(构建脚本)

我已经这样设置了我的字典:

Dictionary<string, BuildingScript> buildingScripts = new Dictionary<string, BuildingScript>();

我正在尝试将其添加到字典中:

buildingScripts.Add("Farm", FarmScript);
buildingScripts.Add("Hunter", HunterScript);
buildingScripts.Add("Fisher", FisherScript);

编译器正在重新识别继承,所以我正在尝试找出我遗漏的内容。

错误信息是:

  • error CS0119: Expression denotes a type', where avariable', value' ormethod group' was expected
  • The best overloaded method match for 'System.Collections.Generic.Dictionary.Add(string, BuildingScript)' has some invalid arguments
  • Argument #2' cannot convertobject' expression to type `BuildingScript'

最佳答案

您的词典已声明为 Dictionary<string, BuildingScript> , 所以它的值应该是 BuildingScript实例 .

考虑差异:FarmScript本身是类型,但是 new FarmScript()是该类型的实例。

所以你的代码应该是这样的:

buildingScripts.Add("Farm", new FarmScript());
buildingScripts.Add("Hunter", new HunterScript());
buildingScripts.Add("Fisher", new FisherScript());

关于c# - 创建字典<string, class>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35740974/

相关文章:

.net - Azure Active Directory 登录连接关闭异常

.net - NuGet 和 Git 子模块

python - 比使用集合更快的比较字典的方法

python - 将字典的字典(大小未知)写为矩阵

c# - 将静态方法附加到类而不是类实例的最佳方法是什么?

dictionary - Groovy - 在对象实例化期间忽略映射中的额外属性

c# - SSIS:创建文件夹的相同脚本。不同的结果?

c# - ToList()——它会创建一个新列表吗?

java - 解码 IBM/360 列二进制格式的十六进制数

c# - 如何在 Silverlight C# for WP7 中使用 NavigationService 作为同步回调的结果?