在表单之间传递数组和在数组中管理
我想将一个数组从Form1传输到Form2,然后在Form2上添加一些值到数组。 在Form1按钮上单击我把这段代码:
int[] arrayOfInt = new int[4]; arrayOfInt[0] = 19; arrayOfInt[1] = 12; Form2 frm2 = new Form2(); frm2.TakeThis(arrayOfInt); frm2.Show();
在form2中,我创建了TakeThis(int[])
,它捕获form1中的值并在标签上显示数组的值。 现在,我无法想象如何向数组添加一些值。 例如arrayOfInt[2]
和arrayOfInt[3]
并发送到Form3。
编辑 :
我决定使用List来存储我的数据,但最后我必须将列表转换为数组,因为我正在对数据进行一些报告和数学运算。
此示例与上面的示例不同。 在此商店中,所有来自列表中的文本框,combox的输入。 最后,我需要将列表转换为数组。
我做了什么,我创建了一个新的全局类:
static class List{ static List list; public static void NewList(){ list=new List(); } public static void Save(string value){ list.Add(value); } public static void Display(){ foreach(var value in list){ MessageBox.Show(value); } } }
数据插入表单之间,
List.save(some_strings); ...
但最后我需要转换数组中的列表。 我google了,我找到了ToArray()
函数,但我不知道如何在我的代码中使用。 我尝试过属性,但我无法进行转换。 请帮忙。
Edit2我找到了解决方案。 在全局静态类List中,我创建了一个返回字符串List的方法:
public static List GetList(){ return list; }
然后,我在Form2上创建了一个新的空字符串列表。 将旧列表复制到新列表并将其转换为数组。
List li=new List(); li=List.GetList(); string[] temp=li.ToArray();
如果需要添加项目所需的数据结构,请不要使用数组。
使用像List
这样的通用集合。
在您的情况下,整数列表将是List
。
IList listOfInt = new List (); listOfInt.Add(19); listOfInt.Add(12); Form2 frm2 = new Form2(); frm2.TakeThis(listOfInt); frm2.Show();
在Form2
,您的TakeThis
函数如下所示:
public voidTakeThis(IList listOfInt) { listOfInt.Add(34); }
将列表传递给另一个表单时也是如此,因为List
是引用类型,而数组是值类型。 如果您不知道这意味着什么,请参阅此文章 。
而是使用ArrayList
甚至更好的IList
。 数组无法在C#中resize
你必须在frm2.TakeThis()
方法上使用ref
参数:
这是一篇关于它的MSDN文章: 使用ref和out传递数组(C#编程指南) 。
void TakeThis(ref Int32[] array) { // Change array }
并使用像:
frm2.TakeThis(ref arrayOfInt);
如果要保持对它们的更改,则需要通过引用传递数组。
如果不能使用Array
使用System.Collections.Generic.List
类的Collection
。
使用List
并使用oList.Add(item)
方法添加元素,因为数组在oList.Add(item)
是固定的(在初始化时已经给出了它的大小)但是如果你想不惜任何代价使用数组,那么创建一个逻辑创建一个大小为Old + new added元素的新数组并返回该数组。
更新我相信你遇到了问题,因为你已经取代了String或者Int。
List oIntList = new List (); oIntList.Add(1); oIntList.Add(3); oIntList.Add(4); oIntList.Add(5); int[] oIntArr = oIntList.ToArray();