C#使用多重的字典Dictionary

使用多重字典是我在需要使用多重判断进行赋值时候想到的一个使用办法,而使用字典来取代多重判断可以减少代码量以及效率,但是会增加空间。所以其本质是通过空间来换取效率。

怎么理解我说的东西呢?加入需要四个bool才能确定某个值,那么一共会有16种情况,用if语句会变得很长,而且还需要四层判断。


好了,讲了这个来讲讲怎么给多重字典赋值。

先来个两重字典。

    //定义字典
    Dictionary<string, string> openWith = new Dictionary<string, string>();
    //添加一重元素
    openWith.Add("txt", "notepad.exe");
    openWith.Add("bmp", "paint.exe");
    openWith.Add("dib", "paint.exe");
    openWith.Add("rtf", "wordpad.exe");

接下来来个三重字典。

    //定义字典
    Dictionary<string, Dictionary<string,string>> openWith = 
    new Dictionary<string, Dictionary<string,string>>();
    //添加一重元素
    openWith.Add("txt", new Dictionary<string,string>);
    //再添加一重元素
    openwith["txt"].Add("bmp", "paint.exe");
   //openwith["txt"]["bmp"]会等于"paint.exe"

看了三重的应该就知道四重的了。

    //定义字典
    Dictionary<string, Dictionary<string,Dictionary<string,string>>> openWith = 
    new Dictionary<string, Dictionary<string,Dictionary<string,string>>>();
    //添加一重元素
    openWith.Add("txt", new Dictionary<string,Dictionary<string,string>>);
    //再添加一重元素
    openwith["txt"].Add("bmp", new Dictionary<string,string>);
    //再添加一重元素
    openwith["txt"]["bmp"].Add("1","A");
   //openwith["txt"]["bmp"]["1"]会等于"A"

总之就是想剥笋一样一层一层地初始化,然后赋值。

猜你喜欢

转载自blog.csdn.net/qq_42987967/article/details/118558112