在C#中需要有关对象初始化的帮助 [英] Need help with object initialization in C#
问题描述
class clsCustomer {
public int custid {get; set;}
public clsOrder [] objOrders {get;设置;}
}
class clsOrder {
public int OrderId {get; set;}
public int ProductId {get; set;}
public int Quantity {get;设置;}
}
需要为clsCustomer的对象分配值以及订单详情如下。
clsCustomer objCustomer = new clsCustomer();
objCustomer.custid = 123;
objCustomer.objOrders [0] .OrderId = 25255525; (在此行获取空引用异常。)
我尝试过:
尝试在clsCustomer的构造函数中初始化clsOrder但仍然出错。
class clsCustomer {
public int custid {get; set;}
public clsOrder[] objOrders{get; set;}
}
class clsOrder{
public int OrderId {get; set;}
public int ProductId {get; set;}
public int Quantity {get; set;}
}
Need to assign values to the object of clsCustomer along with order details as below.
clsCustomer objCustomer = new clsCustomer();
objCustomer.custid = 123;
objCustomer.objOrders[0].OrderId = 25255525; (Getting null reference exception at this line.)
What I have tried:
Tried initializing clsOrder inside constructor of clsCustomer but still getting error.
推荐答案
clsCustomer objCustomer = new clsCustomer();
objCustomer.custid = 123;
objCustomer.objOrders = new clsOrder[] {new clsOrder() { OrderId = 25255525 } };
使用新
Creating
objOrders
with new
clsOrder []
clsOrder[]
并指定
{new clsOrder() { OrderId = 25255525 } }
。
你可以只是声明一个数组属性并使用它 - 创建变量时它是一个空链接,因为系统不知道数组应该有多大。
将代码添加到构造函数中创建数组你应该没问题:
You can't just declare an array property and just use it - it's an "empty link" when the variable is created, because the system has no idea how big the array should be.
Add code to your constructor to create the array and you should be fine:
public class clsCustomer
{
public int custid {get; set;}
public clsOrder[] objOrders{get; set;}
public clsCustomer(int arrayNeeded = 10)
{
objOrders = new clsOrder[arrayNeeded];
}
}
这篇关于在C#中需要有关对象初始化的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!