c# - 在表单之间传递数组并在数组中管理

标签 c# arrays parameter-passing

我想将一个数组从 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。

编辑:

我决定使用一个列表来存储我的数据,但最后我必须转换一个 列出一个数组,因为我正在对数据进行一些报告和数学运算。

这个例子与上面的例子不同。在此存储列表中文本框、组合框的所有输入。最后,我需要将列表转换为数组。

我做了什么 我创建了一个新的全局类:

static class List{

   static List<string> list;

   public static void NewList(){
   list=new List<string>();
   }

   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);
 ...

但最后我需要将列表转换为数组。我用谷歌搜索并找到了 ToArray() 函数,但我不知道如何在我的代码中使用。我尝试使用属性,但无法进行转换。请帮忙。

编辑2 我找到了解决方案。 在全局静态类列表中,我创建了一个返回字符串列表的方法:

public static List<string> GetList(){
              return list;
               }

然后,我在 Form2 上创建了一个新的空字符串列表。将旧列表复制到新列表并将其转换为数组。

List<string> li=new List<string>();
li=List.GetList();
string[] temp=li.ToArray();

最佳答案

如果您想要一个需要添加项目的数据结构,请不要使用数组。

使用像 List<T> 这样的通用集合.

在您的情况下,整数列表将是 List<int> .

IList<int> listOfInt = new List<int>();
listOfInt.Add(19);
listOfInt.Add(12);
Form2 frm2 = new Form2();
frm2.TakeThis(listOfInt);
frm2.Show();

何时开启Form2 , 你的 TakeThis函数看起来像这样:

public voidTakeThis(IList<int> listOfInt)
{
  listOfInt.Add(34);
}

这也适用于将列表传递给另一个表单,如 List是引用类型,而数组是值类型。如果您不知道这意味着什么,请参阅 this article .

关于c# - 在表单之间传递数组并在数组中管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4469222/

相关文章:

php - 检查 JSON 关联数组中是否存在值

c - 颠倒c中的字节顺序

C# 将子列表用作基本列表

c# - 根据另一个对象的类型选择/使用具有通用参数的接口(interface)的实现

c# - 我无法让 Visual Studio 2015 更改新版本的程序图标

arrays - 使用芬威克树或 BIT 的数组中非递减子序列的最大总和

c - 将参数结构传递给 C 中的函数

mysql - 将数组传递给 MySQL 存储例程

c# - 在 Windows Phone 7 上创建视频文件

用于 win32 或 C++ 的 C#