用JSON语法实例化一个锯齿数组

本文关键字:一个 数组 JSON 语法 实例化 | 更新日期: 2023-09-27 17:49:15

我有一个XSD.exe生成的类。我使用的是一种简单的控制反转。我的测试对象可以正常工作,直到我添加了这个花哨的XML片段:

  <items>
    <item>
      <model>1000</model>
      <description>Torque wrench</description>
      <material>1545454</material>
      <lot>3</lot>
      <serial></serial>
      <transferQty>1</transferQty>
      <shipQty></shipQty>
    </item>
    <item>
         //..item 2
    </item>
    <item>
          //...item 3
    </item>
  </items>
</itemOrder>

现在,GeneratedByXsdClass对象的创建被破坏了。

    GeneratedByXsdClass.items = new itemOrderItemsItem[][]{
        new itemOrderItemsItem[1][]//this hardcoded 1 bothers me.  better way?
        {
            new itemOrderItemsItem[]
            {
                new itemOrderItemsItem()
                {
                    model = "1000",
                    description = "Torque Wrench",
                    material = "10002525",
                    lot = "3",
                    serial = "",
                    transferQty = "1",
                    shipQty = ""
                }
            }
        }
    };

编译错误:

Error   3   Cannot implicitly convert type 'itemOrderItemsItem[][]' to 'itemOrderItemsItem[]'   

我愿意修改xsd.exe生成的类,如果这使生活更容易。我只想让<item>重复N次

用JSON语法实例化一个锯齿数组

将示例简化为:

new int[][]{
    new int[1][]//this hardcoded 1 bothers me.  better way?
    {
        new int[]
        {
            4
        }
    }
}

现在您应该能够看到问题所在;你试图将int[][]放入int[][]中,编译器说它期望int[]。删除带有注释的行:

new int[][]{
    new int[]
    {
        4
    }
}

在你的代码中是等价的:

GeneratedByXsdClass.items = new itemOrderItemsItem[][]{
    new itemOrderItemsItem[]
    {
        new itemOrderItemsItem()
        {
            model = "1000",
            description = "Torque Wrench",
            material = "10002525",
            lot = "3",
            serial = "",
            transferQty = "1",
            shipQty = ""
        }
    }
};