【问题标题】:How to add additional value to an array?如何为数组添加附加值?
【发布时间】:2017-06-05 21:29:00
【问题描述】:

我目前正在创建一个程序,只要特定用户有足够的资金,用户就可以使用打印机。

我目前遇到的问题是,如果用户选择彩色打印而不是黑白打印,那么每张纸的价格都会上涨。

如何为已经存在的数组添加值?

这是我的代码...

printers[0] = new Printer("printer1", 0.10M);
            printers[1] = new Printer("printer2", 0.08M);
            printers[2] = new Printer("printer3", 0.05M);
            printers[3] = new Printer("printer4", 0.15);
            printers[4] = new Printer("printer5", 0.09M);

            foreach (Printer r in mPrinters)
            {
                if (printer != null)
                    printerCombo.Items.Add(r.getName());
            }

【问题讨论】:

  • 改用列表
  • 数组是固定大小的设计。如果想要一个可以添加、删除、插入的集合,请查看 System.Collection.GenericSystem.Collection.ObjectModel 中的类

标签: c# arrays winforms int


【解决方案1】:

技术上,你可以Resize数组:

 Array.Resize(ref printers, printers.Length + 1);

 printers[printers.Length - 1] = new Printer("printer6", 0.25M);

不过,更好的方法是将集合类型:array 更改为 List<T>:

 List<Printer> printers = new List<Printer>() {
   new Printer("printer1", 0.10M),
   new Printer("printer2", 0.08M),
   new Printer("printer3", 0.05M),
   new Printer("printer4", 0.15),
   new Printer("printer5", 0.09M), }; 

 ...

 printers.Add(new Printer("printer6", 0.25M));

【讨论】:

  • Resize 创建新的 a 将旧数组的所有内容复制到新数组中。它不会调整原始数组的大小。
  • @Fran:你说得很对(这就是为什么我们在调用Array.Resize 时使用ref 传递数组)。然而,恕我直言,这种底层行为并不重要:我们得到了增加其Length 的数组,并且我们知道数组不应该改变它们的大小(所以我们不应该经常使用Array.Resize)跨度>
【解决方案2】:

数组具有固定大小 - 创建大小为 10 的数组后,您不能再添加一个元素(以使大小变为 11)。

使用List&lt;Printer&gt;:

List<Printer> printers = new List<Printer>();
printers.Add(new Printer("printer2", 0.08M));
//add all items

你也可以通过索引访问元素:

var element = printers[0];

使用List,您可以更改其大小、添加和删除元素。

【讨论】:

    【解决方案3】:

    数组是固定长度的。您需要将值复制到新数组中或使用 List、List 或 ArraryList。

    【讨论】:

    • 不,它们不是一成不变的。他们只是有一个固定的长度。两种不同的东西。
    • 真的。更新答案。
    • ArrayList 已经过时了,我们不建议使用它。 List 是要走的路。
    • 是的。我更喜欢吝啬类型的集合,但它仍然是框架的一部分
    猜你喜欢
    • 2021-05-03
    • 2015-12-20
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 2022-11-26
    相关资源
    最近更新 更多