问题描述
|
我是C#的新手,我来自Ruby。我还有很多东西要学习,这就是为什么我要问以下问题:
目标:
1)我想创建一个字典,将字符串作为键,将任何想要的对象类型作为值。像这样:
Dictionary<string,T>
2)但这还不是全部。我还想要一个\“ Master \\”字典,其中字符串作为键,而上述字典作为值。
像这样:
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,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,object>>();
TempData.Add(\"DataInfo\",new Dictionary<string,DataInfo>());
TempData.Add(\"Maps\",Map>());
TempData.Add(\"Tilesets\",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\",DataInfo>());
TempData.Add(\"Maps\",Map>());
TempData.Add(\"Tilesets\",Tileset>());
// Create GameData dictionary and copy TempData into it.
GameData = new Dictionary<string,object>(TempData);
我显然在这里做错了甚至是违法的,我只需要知道它是什么以及如何解决它!
我一直在自己做很多研究,但是没有发现任何可以帮助我的事情。
我已经看过如何制作字典词典,但是我不太确定如何告诉字典不要关心Value中的对象类型。
我知道\“ T \”可能在这里有用,但我真的不知道如何使用它,因为它总是告诉我\“找不到类型或名称空间名称\'T \'\”
所以我该怎么做?
提前致谢
-萨沙
解决方法
问题是您没有将typedef与创建的对象匹配。将您的代码更改为此:
public void 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,object>());
TempData.Add(\"Maps\",object>());
TempData.Add(\"Tilesets\",object>());
// Create GameData dictionary and copy TempData into it.
GameData = new Dictionary<string,object>>(TempData);
}
, 您可以将所有字典改变为字符串,对象...。
但是也许,因为您是来自Ruby的人,所以还有另一个问题.....
将所有内容放入字典中,然后在提取时必须弄清楚它们是什么类型,可能不是最好的方法。在类型化语言中,通常最好对所有类型进行类型化
也许最好有一个带有类型的字典的类型化对象...
class GameResources
{
public Dictionary<string,Map> Maps { get; set;}
public Dictoinary<string,Tileset> Tileset { get; set; }
}
等等...或者可能有些想法,在您的情况下,另一个类结构可能更合适