简体   繁体   English

为什么向数组类型 object 声明和赋值会抛出超出范围的错误?

[英]Why declaring and assigning values to array type object is throwing out of bound error?

I have defined this:我已经定义了这个:

DT_OrderResponseOrderHeaderOperation[] HeaderOperation = new DT_OrderResponseOrderHeaderOperation[] { };
HeaderOperation[0].DAUNO = Convert.ToString(dr["Duration"]);
HeaderOperation[0].DAUNE = Convert.ToString(dr["DurationUnit"]);

But it throws error:但它会引发错误:

Index was outside the bounds of the array.指数数组的边界之外。

DT_OrderResponseOrderHeaderOperation is of type array. DT_OrderResponseOrderHeaderOperation是数组类型。

You need to add length specifier to declare array.您需要添加长度说明符来声明数组。 Length specifier indicates that how many elements are contained by your array.长度说明符指示数组包含多少元素。 See: Single-Dimensional Arrays参见: 单维 Arrays

DT_OrderResponseOrderHeaderOperation[] HeaderOperation = new DT_OrderResponseOrderHeaderOperation[1];
HeaderOperation[0] = new DT_OrderResponseOrderHeaderOperation()
{
    DAUNO = Convert.ToString(dr["Duration"]),
    DAUNE = Convert.ToString(dr["DurationUnit"])
};

Or you can use this Array Initialization as follow.In this case, the length specifier is not needed because it is already supplied by the number of elements in the initialization list.或者您可以按如下方式使用此数组初始化。在这种情况下,不需要长度说明符,因为它已经由初始化列表中的元素数提供。

DT_OrderResponseOrderHeaderOperation[] HeaderOperation = new DT_OrderResponseOrderHeaderOperation[]
{
    new DT_OrderResponseOrderHeaderOperation()
    {
        DAUNO = Convert.ToString(dr["Duration"]),
        DAUNE = Convert.ToString(dr["DurationUnit"])
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM