如何为具有数组变量的类声明和赋值
本文关键字:声明 赋值 变量 数组 | 更新日期: 2023-09-27 18:35:15
当数组变量在不同的类中声明时,如何为其赋值?以下是示例代码,以便于理解我的问题:-
// Below is a class customer that has three parameters:
// One string parameter and Two int array parameter
public class Customer
{
public string invoiceFormat { get; set; }
public int [] invoiceNumber { get; set; }
public int [] customerPointer { get; set; }
public Customer(
string invoiceFormat,
int[] invoiceNumber,
int[] customerPointer)
{
this.invoiceFormat = invoiceFormat;
this.invoiceNumber = invoiceNumber;
this.customerPointer = customerPointer;
}
}
// How to assign value for invoiceNumber or customerPointer array in
// different windows form?
// The following codes is executed in windowsform 1
public static int iValue=0;
public static Customer []c = new Customer [9999];
c[iValue] = new Customer(textBox16.Text, invoiceNumber[0].iValue + 1,
customerPointer[0].iValue);
// I have an error that the name 'invoiceNumber and customerPointer'
// does not exist inthe current context
你所拥有的
c[iValue] = new Customer(textBox16.Text, invoiceNumber[0].iValue + 1, customerPointer[0].iValue);
这是完全错误的,这就是为什么您收到错误的原因:名称"发票编号和客户指针"在当前上下文中不存在
您永远不会为发票编号或客户指针声明任何数组。 这两个都是你班的成员,我认为你感到困惑的地方。 我什至不会猜测 invoiceNumber[0].iValue +1 是什么,因为 int 没有成员,它是一种数据类型
因此,要解决此问题,我们将执行以下操作
//create some arrays
int[] invoicesNums = new int[]{1,2,3,4,5};
int[] customerPtrs = new int[]{1,2,3,4,5};
//create a new customer
Customer customer = new Customer("some invoice format", invoicesNums, customerPtrs);
//add the customer to the first element in the static array
Form1.c[0] = customer;
好的,这就是你应该这样做的方式,但是,我真的认为你需要停下来更深入地研究类、数组、数据类型和 OOP,因为当你在程序的道路上走得更远时,这将使你免于头疼。
您正在尝试使用尚不存在的值。 看看你的构造函数:
public Customer(string invoiceFormat, int[] invoiceNumber, int[] customerPointer)
{
this.invoiceFormat = invoiceFormat;
this.invoiceNumber = invoiceNumber;
this.customerPointer = customerPointer;
}
这意味着您需要传递一个字符串、一个完整的int
数组和另一个完整的int
数组。 通过尝试执行此操作:
c[iValue] = new Customer(textBox16.Text, invoiceNumber[0].iValue + 1, customerPointer[0].iValue);
您正在调用尚不存在的变量。 考虑一下构造函数这个词。 这将创建对象并初始化内部变量。 invoiceNumber[]
和customerPointer[]
永远不会通过传递另一个数组参数来分配。 这就是您收到该错误消息的原因。 如果您使用构造函数初始化这些数组,然后传递单个invoiceNumber
和单个customerPointer
,然后将其添加到初始化的数组中,那么这将起作用。 但是,听起来您的内部值不应该是数组,那么您只需为每个参数传递一个int
值。