我必须使用数组进行练习.用户必须输入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 …Run Code Online (Sandbox Code Playgroud) 使用这个问题的答案“如何将字符串添加到 string[] 数组?没有 .Add 函数”我试图使用这个答案来编写一个通用扩展以将元素附加到 .Add 函数generic array。仅使用该Array.Resize()方法效果很好,下面的示例向我的string array
string[] array = new string[] { "Foo", "Bar" };
Array.Resize(ref array, array.Length + 1);
array[array.Length - 1] = "Baz";
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用下面描述的 ArrayExtension 方法时,该方法确实在方法内调整了数组的大小,但是当它返回时数组没有改变?
我的扩展课
public static class ArrayExtensions
{
public static void Append<T>(this T[] array, T append)
{
Array.Resize(ref array, array.Length + 1);
array[array.Length - 1] = append; // < Adds an extra element to my array
}
} …Run Code Online (Sandbox Code Playgroud)