【发布时间】:2011-09-19 22:45:00
【问题描述】:
我是 C# 的新手,我来自 Ruby 背景。我还有很多东西要学,这就是我提出以下问题的原因:
目标: 1)我想创建一个字典,其中字符串作为键,我想要的任何对象类型作为值。像这样的:
Dictionary<string, T>
2) 但这还不是全部。我还想要一个“主”字典,其中字符串作为键,上述字典作为值。 像这样的:
Dictionary<string, Dictionary<string T>>
我希望它是这样的,所以我可以像下面的例子一样工作:
MasterDictionary[Dict1].Add( Thing1 )
MasterDictionary[Dict2].Add( Thing2 )
当前代码: 我正在尝试使用以下代码来实现这一目标
public List<string> DataTypes;
public Dictionary<string, Dictionary<string, object>> TempData;
public Dictionary<string, Dictionary<string, object>> GameData;
public Session()
{
// Create a list of all Data Types.
DataTypes = new List<string>();
DataTypes.Add("DataInfo");
DataTypes.Add("Maps");
DataTypes.Add("Tilesets");
// Create and populate TempData dictionary.
TempData = new Dictionary<string, Dictionary<string, object>>();
TempData.Add("DataInfo", new Dictionary<string, DataInfo>());
TempData.Add("Maps", new Dictionary<string, Map>());
TempData.Add("Tilesets", new Dictionary<string, Tileset>());
// Create GameData dictionary and copy TempData into it.
GameData = new Dictionary<string, object>(TempData);
}
问题: 我收到以下错误
1) 'System.Collections.Generic.Dictionary>.Add(string, System.Collections.Generic.Dictionary)' 的最佳重载方法匹配有一些无效参数
2)错误 10 参数 1:无法从 'System.Collections.Generic.Dictionary>' 转换为 'System.Collections.Generic.IDictionary'
以下行用红色下划线标记
TempData.Add("DataInfo", new Dictionary<string, DataInfo>());
TempData.Add("Maps", new Dictionary<string, Map>());
TempData.Add("Tilesets", new Dictionary<string, Tileset>());
// Create GameData dictionary and copy TempData into it.
GameData = new Dictionary<string, object>(TempData);
我显然在这里做错了甚至违法,我只需要知道它是什么以及如何解决它!
我自己做了很多研究,但没有发现任何可以帮助我的东西。 我已经看到如何制作字典字典,但我不太确定如何告诉字典不要关心 Value 中的对象类型。
我知道“T”在这里可能有用,但我真的不知道如何使用它,因为它总是告诉我“找不到类型或命名空间名称 'T'”
那我该怎么办?
提前致谢 - 萨沙
【问题讨论】:
标签: c# generics dictionary types