You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

初始化SOAP请求数组属性时遇Object reference未实例化错误

解决Object Reference Not Set to an Instance of an Object错误

这个报错的核心原因很清晰:你已经创建了OrderInformation_type的实例,但它的ItemInformation数组还处于未初始化状态(值为null),直接通过[0]索引访问并赋值自然会触发空引用错误。

修复方案

你需要先初始化这个数组,再为数组内的元素创建实例。这里提供两种常用的修复方式:

方式一:直接初始化指定长度的数组

如果提前知道需要的元素数量,可以先创建对应长度的数组,再逐个赋值:

WindowsFormsApplication1.ServiceReference1.OrderInformation_type orderinfo = new ServiceReference1.OrderInformation_type();
orderinfo.Header = new ServiceReference1.Header_type();
orderinfo.Header.AccountNumber = 496570;
orderinfo.Header.DistributorIdentifier = ServiceReference1.Header_typeDistributorIdentifier.MBA;
orderinfo.PromotionInformation = new ServiceReference1.PromotionInformation_type();

// 先初始化数组,这里假设你需要1个元素,所以长度设为1
orderinfo.ItemInformation = new ServiceReference1.ItemInformation_type[1];

// 现在可以正常给数组元素赋值了
orderinfo.ItemInformation[0] = new ServiceReference1.ItemInformation_type();
orderinfo.ItemInformation[0].ItemID = "95847";
orderinfo.ItemInformation[0].ItemIDType = ServiceReference1.ItemInformation_typeItemIDType.D;
orderinfo.ItemInformation[0].Quantity = 1;

方式二:用列表动态添加元素(更灵活)

如果不确定需要多少个ItemInformation_type实例,推荐用List<T>来动态添加,最后再转换为数组:

WindowsFormsApplication1.ServiceReference1.OrderInformation_type orderinfo = new ServiceReference1.OrderInformation_type();
orderinfo.Header = new ServiceReference1.Header_type();
orderinfo.Header.AccountNumber = 496570;
orderinfo.Header.DistributorIdentifier = ServiceReference1.Header_typeDistributorIdentifier.MBA;
orderinfo.PromotionInformation = new ServiceReference1.PromotionInformation_type();

// 创建列表并添加元素
var itemList = new List<ServiceReference1.ItemInformation_type>();
var newItem = new ServiceReference1.ItemInformation_type();
newItem.ItemID = "95847";
newItem.ItemIDType = ServiceReference1.ItemInformation_typeItemIDType.D;
newItem.Quantity = 1;
itemList.Add(newItem);

// 将列表转换为数组赋值给ItemInformation
orderinfo.ItemInformation = itemList.ToArray();

额外说明

从WSDL生成的代理类中,引用类型的数组默认是null,不会自动初始化。而Header和PromotionInformation这类单个对象类型,你已经手动创建了实例,所以没有问题;但数组必须单独完成初始化操作后,才能访问其索引位置的元素。

内容的提问来源于stack exchange,提问作者Azher Aleem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:01:08