我必须做一个使用数组的练习。用户必须输入 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();
}
所以我的问题归结为:
如何让用户输入多于一批的输入? 比如第一次用户会输入元素的信息(socket number, price and name),但是我需要让用户输入其他元素的更多信息?
假设数组中有多个项目,如何显示数组中每个项目的 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/