如何在不同的类中声明数组变量时为其赋值?以下是示例代码,以便更轻松地了解我的问题: -
// 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
答案 0 :(得分:1)
你有什么
c[iValue] = new Customer(textBox16.Text, invoiceNumber[0].iValue + 1, customerPointer[0].iValue);
这是完全错误的并且是您收到错误的原因:当前上下文中不存在名称'invoiceNumber和customerPointer'
您永远不会为invoiceNumber或CustomerPointers声明任何数组。这两个都是你班级的成员,我认为你会感到困惑。我甚至不会猜测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,因为当你走得更远时,这将使你免于头痛与您的计划。
答案 1 :(得分:0)
您正在尝试使用尚不存在的值。看看你的构造函数:
public Customer(string invoiceFormat, int[] invoiceNumber, int[] customerPointer)
{
this.invoiceFormat = invoiceFormat;
this.invoiceNumber = invoiceNumber;
this.customerPointer = customerPointer;
}
这意味着您需要传递一个字符串,一个int
的完整数组和另一个int
的COMPLETE数组。试图这样做:
c[iValue] = new Customer(textBox16.Text, invoiceNumber[0].iValue + 1, customerPointer[0].iValue);
您正在调用尚不存在的变量。想想构造函数这个词。这会创建对象并初始化内部变量。传递另一个数组参数永远不会分配invoiceNumber[]
和customerPointer[]
。这就是您收到该错误消息的原因。如果您使用构造函数初始化这些数组,然后传递单个invoiceNumber
和单个customerPointer
,然后将其添加到初始化数组中,那么这将起作用。但是,听起来你的内部值不应该是数组,那么你就可以为每个参数传递一个int
值。