[英]How to add value to an array of object in C#
I am consuming a third party web service and I want to add value to match the service reference class, and i am not sure how to add value to the following: 我正在使用第三方Web服务,我想增加价值以匹配服务引用类,而且我不确定如何为以下各项增加价值:
in reference: 参考:
public partial class UserInfor: object, System.ComponentModel.INotifyPropertyChanged
{
private ABC[] listOfABCField;
public ABC[] ListOfABC
{
get {
return this.listOfABCField;
}
set {
this.listOfABCField = value;
this.RaisePropertyChanged("ListOfABC");
}
}
}
public partial class ABC : object, System.ComponentModel.INotifyPropertyChanged
{
private string ipField;
private string fristNameField;
private string lastNameField;
}
////////////////////////////////////////////////////// in my service.asmx file have tried to put value as below: in below code i got exception in line ABC[] abc=new ABC[0]; ///////////////////////////////////////////////////// ////在我的service.asmx文件中,尝试按如下所示放置值:在下面的代码中,我在ABC [] abc = new ABC [0]行中遇到异常; error code:(NullReferenceException)
错误代码:(NullReferenceException)
UserInfor user = new UserInfor();
ABC[] abc=new ABC[0];
abc[0].firstName= "petter";
abc[0].lastName = "lee";
user.ListOfABC = abc[1];
i also tried in below code i got exception in line user.ListOfABC[0] = abc; 我也在下面的代码中尝试过我在user.ListOfABC [0] = abc;行中异常。 error code:(NullReferenceException)
错误代码:(NullReferenceException)
UserInfor user = new UserInfor();
ABC abc=new ABC[0];
abc.firstName= "petter";
abc.lastName = "lee";
user.ListOfABC[0] = abc;
any idea how to add abc to user class ? 任何想法如何将abc添加到用户类? thank you in advance
先感谢您
This'll probably be easier if you use a List<>
instead of an array. 如果使用
List<>
而不是数组,这可能会更容易。 Change the property: 更改属性:
private List<ABC> listOfABCField;
public List<ABC> ListOfABC
{
// etc.
}
Don't forget to initialize it in the class' constructor so it's not null: 不要忘记在类的构造函数中对其进行初始化,因此它不为null:
public UserInfor()
{
listOfABCField = new List<ABC>();
}
Then you can just add an object to it, which doesn't need any of the array syntax you were trying to use: 然后,您可以向其添加一个对象,该对象不需要您尝试使用的任何数组语法:
UserInfor user = new UserInfor();
ABC abc = new ABC();
abc.firstName= "petter";
abc.lastName = "lee";
user.ListOfABC.Add(abc);
You are doing it wrong, first instantiate the array, if you know in advance how many items it would contain then specify that as well in the square brackets like: 您做错了,首先实例化该数组,如果您事先知道它将包含多少个项目,然后在方括号中指定,例如:
ABC[] abc=new ABC[1]; // this array will contain 1 item maximum
now instantiate that item and then set values of properties : 现在实例化该项目,然后设置属性值:
abc[0] = new ABC(); // instantiating first item of array which is at 0th index
abc[0].firstName= "petter";
abc[0].lastName = "lee";
If you don't know how many item would come in it, then go with @David's suggestion of using List<T>
如果您不知道要输入多少个项目,请遵循@David的使用
List<T>
的建议
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.