[英]C# Dictionary using TValue within another Dictionary
我是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, 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'”
所以我該怎么做?
提前謝謝 - 薩莎
你可以將所有的dictonaries改為string,object ....
但也許,因為你來自Ruby,還有另一個問題......
將所有內容放入字典中然后在提取時必須弄清楚它們的類型可能不是最好的方法。 在打字語言中,通常最好為所有內容制作類型
也許最好有一個帶有類型字典的打字對象......
class GameResources
{
public Dictionary<string, Map> Maps { get; set;}
public Dictoinary<string, Tileset> Tileset { get; set; }
}
等等......或者很可能還有一些想法,在你的情況下,另一個類結構可能更合適
問題是您沒有將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", new Dictionary<string, object>());
TempData.Add("Tilesets", new Dictionary<string, object>());
// Create GameData dictionary and copy TempData into it.
GameData = new Dictionary<string, Dictionary<string, object>>(TempData);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.