创建字典<string,dictionary <t,=“”t [] =“”> []&gt; </string,>

时间:2014-03-20 15:58:03

标签: c# .net

在C#中,实例化和初始化包含字典数组值的字典的语法是什么,这些字典本身包含数组作为值?

例如,(我相信),

Dictionary<string, Dictionary<string, string[]>[]>?

以下是我正在尝试做的一个例子:

private static readonly Dictionary<string, Dictionary<string, DirectoryInfo[]>[]> OrderTypeToFulfillmentDict = new Dictionary<string, Dictionary<string, DirectoryInfo[]>>()
    {
        {"Type1", new [] 
                { 
                    ProductsInfo.Type1FulfillmentNoSurfacesLocations, 
                    ProductsInfo.Type2FulfillmentSurfacesLocations 
                } 
        }
    }

其中Type1Fulfillment ...和Type2Fulfillment ...已构造为

Dictionary<string, DirectoryInfo[]>. 

这会抛出以下编译器错误:

"Cannot convert from System.Collections.Generic.Dictionary<string, System.IO.DirectoryInfo[]>[] to System.Collections.Generic.Dictionary<string, System.IO.DirectoryInfo[]>"

编辑:问题是,正如Lanorkin指出的那样,我错过了新[]中的最终Dictionary<string, Dictionary<string, DirectoryInfo[]>>()。不过,不言而喻,这可能不是任何人应该首先尝试做的事情。

5 个答案:

答案 0 :(得分:5)

您所看到的内容看起来是正确的,但您正在做的事情有一个真实的code smell,它会导致一些严重的technical debt

对于初学者而言,不是在类中使用内部Dictionary<string, string[]>模型,而是使用适合您尝试建模的方法。否则,访问此类型的任何人都无法了解其真正建模的内容。

答案 1 :(得分:2)

这样的事情:

var dic = new Dictionary<string, Dictionary<int, int[]>[]>
        {
            {
                "key1", 
                new[]
                {
                    new Dictionary<int, int[]>
                    {
                        {1, new[] {1, 2, 3, 4}}
                    }
                }}
        };

答案 2 :(得分:1)

Dictionary<string, Dictionary<string, string[]>[]> complexDictionary = new Dictionary<string, Dictionary<string, string[]>[]>();

或使用var关键字:

var complexDictionary = new Dictionary<string, Dictionary<string, string[]>[]>();

答案 3 :(得分:1)

以下内容完全有效

     // array of dictionary
     Dictionary<int, string[]>[] matrix = new Dictionary<int, string[]>[4];

//Dictionary of string and dictionary array
 Dictionary<string, Dictionary<string, string[]>[]> dicOfArrays= new Dictionary<string, Dictionary<string, string[]>[]>();

答案 4 :(得分:0)

 private static readonly Dictionary<string, Dictionary<string, DirectoryInfo[]>> 

OrderTypeToFulfillmentDict = new Dictionary<string, Dictionary<string, DirectoryInfo[]>>()
     {
         {"Type1", new [] 
            { 
                ProductsInfo.Type1FulfillmentNoSurfacesLocations, 
                ProductsInfo.Type2FulfillmentSurfacesLocations 
            } 
    }
}

变量定义中的类型错误。删除最后的“[]”,因为您不需要一组字典。