C#Dictionary在另一个词典中使用TValue

Sas*_*sha 5 c# generics dictionary types

我是C#的新手,我来自Ruby背景.我还有很多需要学习的东西,这也是我提出以下问题的原因:

目标:1)我想创建一个字符串作为键和我想要的任何对象类型作为值.像这样的东西:

Dictionary<string, T>
Run Code Online (Sandbox Code Playgroud)

2)但并非全部.我还想要一个"Master"字典,字符串作为键,上面描述的字典作为值.像这样的东西:

Dictionary<string, Dictionary<string T>>
Run Code Online (Sandbox Code Playgroud)

我希望它是这样的,所以我可以像下面的例子一样工作:

MasterDictionary[Dict1].Add( Thing1 )
MasterDictionary[Dict2].Add( Thing2 )
Run Code Online (Sandbox Code Playgroud)

当前代码:我正在尝试使用以下代码实现此目的

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);
        }
Run Code Online (Sandbox Code Playgroud)

问题:我收到以下错误

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);
Run Code Online (Sandbox Code Playgroud)

我在这里显然做错了甚至非法,我只需要知道它是什么以及如何解决它!

我自己做了很多研究,但没有找到任何可以帮助我的事情.我已经看过如何制作字典词典,但我不太确定如何告诉字典不关心Value中的对象类型.

我知道"T"可能在这里有用,但我真的不知道如何使用它,因为它总是告诉我"无法找到类型或命名空间名称'T'"

所以我该怎么做?

提前谢谢 - 萨莎

Ed *_*tes 1

问题是您的 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);
}
Run Code Online (Sandbox Code Playgroud)