简体   繁体   English

如何为数组添加附加值?

[英]How to add additional value to an array?

I am currently creating a program where the user can use a printer as long as that particular user has enough funds. 我当前正在创建一个程序,只要该特定用户有足够的资金,该用户就可以使用打印机。

The current issue I am having is that if the user chooses to have colour printing instead of black and white then the price for each piece of paper goes up. 我当前遇到的问题是,如果用户选择使用彩色打印而不是黑白打印,那么每张纸的价格都会上涨。

How do I add value to an already existing array? 如何为现有数组增加价值?

Here is my code... 这是我的代码...

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());
            }

Technically, you can Resize the array: 从技术上讲,您可以调整数组大小

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

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

However, a much better approach is to change the collection type: array into List<T> : 但是,更好的方法是将集合类型更改为:将数组更改为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));

Arrays have fixed size - after you created array with size 10 you can't add one more element (to make size 11). 数组具有固定的大小-创建大小为10的数组后,不能再添加一个元素(使大小为11)。

Use List<Printer> : 使用List<Printer>

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

Also you can access elements by index: 您也可以按索引访问元素:

var element = printers[0];

Using List you can change its size, add and remove elements. 使用List您可以更改其大小,添加和删除元素。

Arrays are fixed length. 数组是固定长度的。 You need to copy the values into a new array or use an List, List<>, or ArraryList. 您需要将值复制到新数组中,或使用List,List <>或ArraryList。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM