在本文中,我将解释如何增加数组的大小。
.NET Framework允许我们在判断必要时增加数组的大小。
在C#中,当声明数组变量时,必须指定常量值作为数组的大小
当我们需要增加数组的大小时,有很多情况。
我们可以增加该数字,
我们可以定义自己的方法或者函数以增加数组的大小。
namespace demo_array
{
public class Starter
{
public class Routine
{
public static void IncreaseArray(ref string[] values, int increment)
{
string[] array = new string[values.Length + increment];
values.CopyTo(array, 0);
values = array;
}
}
private static void Show(string[] ns)
{
foreach (string name in ns)
Console.WriteLine("Fruit: " + name);
}
public static void Main()
{
string[] names = new string[4];
Console.WriteLine("Length of Fruits = " + names.Length.ToString());
Console.WriteLine("");
names[0] = "banana";
names[1] = "cherry";
names[2] = "pear";
names[3] = "apple";
Show(names);
Routine.IncreaseArray(ref names, 6);
Console.WriteLine("\nLength of Fruits = " + names.Length.ToString());
Console.WriteLine("");
names[4] = "watermelon";
names[5] = "pomegranate";
names[6] = "grape";
names[7] = "strawberry";
names[8] = "hippophae";
names[9] = "orange";
Show(names);
Console.WriteLine("");
Console.ReadKey();
}
}
}
日期:2020-04-11 22:50:34 来源:oir作者:oir
