c# - 如何在 C# 中扩展数组

标签 c# arrays input

我必须做一个使用数组的练习。用户必须输入 3 个输入(每次输入有关项目的信息),这些输入将被插入到数组中。然后我必须显示数组。

但是,我很难在不更改其中信息的情况下增加数组的长度;以及如何让用户输入另一组输入?这是我目前所拥有的:

public string stockNum;
public string itemName;
public string price;

string[] items = new string[3];

public string [] addItem(string[] items)
{
    System.Console.WriteLine("Please Sir Enter the stock number");
    stockNum = Console.ReadLine();
    items.SetValue(stockNum, 0);
    System.Console.WriteLine("Please Sir Enter the price");
    price = Console.ReadLine();
    items.SetValue(price, 1);
    System.Console.WriteLine("Please Sir Enter the item name");
    itemName = Console.ReadLine();
    items.SetValue(itemName, 2);
    Array.Sort(items);
    return items;
}


public void ShowItem()
{
    addItem(items);
    Console.WriteLine("The stock Number is " + items[0]);
    Console.WriteLine("The Item name is " + items[2]);
    Console.WriteLine("The price " + items[1]);
}

static void Main(string[] args)
{
    DepartmentStore depart = new DepartmentStore();
    string[] ar = new string[3];
    // depart.addItem(ar);
    depart.ShowItem();
}

所以我的问题归结为:

  1. 如何让用户输入多于一批的输入? 比如第一次用户会输入元素的信息(socket number, price and name),但是我需要让用户输入其他元素的更多信息?

  2. 假设数组中有多个项目,如何显示数组中每个项目的 socket 编号、价格和名称?

最佳答案

从 .NET Framework 3.5 开始,对于一维数组,您可以使用 Array.Resize<T>方法:

int[] myArray = { 1, 2, 3 };
// Extend
Array.Resize(ref myArray, 5); // { 1, 2, 3, 0, 0 }
// Shrink
Array.Resize(ref myArray, 2); // { 1, 2 }

Microsoft 文档链接是 here .

This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one. array must be a one-dimensional array.

关于c# - 如何在 C# 中扩展数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/628427/

相关文章:

c# - 如何在其他应用程序中使用新的类方法?

c - 如何检查输入结束? C、找到42

c# - 如何将未转义的 XML 放入类的 XmlText 字段中?

c# - ASP缓存新手-尝试模拟WinForms功能/正确的协议(protocol)

c# - FxCop 对如何消除多余的 castclass 感到困惑

javascript - 禁用所有依赖于阵列的选择选项

c++ - 从字符串数组转换为 char* const

python - 索引错误 : shape mismatch: indexing arrays could not be broadcast together with shapes (2, ) (3,)

c - 在 C 程序中使用 .txt 接收输入

javascript - 等待事件中的变量