如何将值赋给类中的数组类变量 [英] How to assign value to an array class variable which is inside a class
问题描述
public partial class OrderWS
{
private FulfillmentWS[] fulfillmentListField;
public FulfillmentWS[] fulfillmentList
{
get
{
return this.fulfillmentListField;
}
set
{
this.fulfillmentListField = value;
}
}
}
public partial class FulfillmentWS
{
private string fulfillingOutletIdField;
public string fulfillingOutletId
{
get
{
return this.fulfillingOutletIdField;
}
set
{
this.fulfillingOutletIdField = value;
}
}
}
这两个类都在* .cs文件中。我正在尝试访问fulfillingOutletIdField变量并为其分配一个vlue,如下所示。
Both the classes are in same *.cs file. I'm trying to access fulfillingOutletIdField variable and assign a vlue to it, as below.
OrderWS WPObj = new OrderWS();
WPObj.fulfillmentList = new FulfillmentWS[1]; WPObj.fulfillmentList[1].fulfillingOutletId = "1234";
但我在最后一行出错了,说数组索引越界
任何帮助都将不胜感激..
谢谢!
But I've an error in last line, saying "Array Index Out of bounds
"
Any help would be appreciated..
Thanks !
推荐答案
查看您的代码:
Look at your code:
WPObj.fulfillmentList = new FulfillmentWS[1];
WPObj.fulfillmentList[1].fulfillingOutletId = "1234";
您声明一个包含一个元素的数组,并尝试访问它的第二个元素 - C#使用基于零的索引我确定您记得! :笑:
即使我添加
You declare an array with one element, and that try to access the second element of it - C# uses zero based indexes I'm sure you remember! :laugh:
"Even if I add
WPObj.fulfillmentList[0].fulfillingOutletId = "1234";
我有对象参考未设置...错误,我正在寻找一个aswer
>
好的 - 你会的。
想一想:你为WPObj分配了一个元素的数组,但是这个数组不会自动用新对象填充它 - 它是一个数组null值。
您需要创建数组,用对象填充它们,然后访问它们。
I've "Object reference not set..." error, I'm looking for an aswer"
Well yes - you will.
Think about it: You allocated an array of one element to WPObj, but that array doesn't automatically fill itself with new objects - it's an array of null values.
You need to create the array, fill it with objects, and then access them.
WPObj.fulfillmentList = new FulfillmentWS[1];
WPObj.fulfillmentList[0] = new FulfillmentWS();
WPObj.fulfillmentList[0].fulfillingOutletId = "1234";
老实说,我会使用List而不是Array,并创建类中的集合实例,而不是将它留给外界。
To be honest, I'd use a List rather than an Array, and create the collection instance inside the class, rather than leaving it up to the outside world.
这篇关于如何将值赋给类中的数组类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!