如何在 C# 中动态创建数组?
如何在 C# 中动态创建数组?
我想要补充一下Natrium的回答,泛型集合也支持这个.ToArray()方法。
List<string> stringList = new List<string>();
stringList.Add("1");
stringList.Add("2");
stringList.Add("3");
string[] stringArray = stringList.ToArray();
首先创建一个ArrayList,添加/删除项目。然后使用ArrayList.ToArray()
方法。
这样就得到了你的数组!
object foo = Array.CreateInstance(typeof(byte), length);
好的,数组初始化总是让我 每次都犯错。所以我花了10分钟时间来做对它。
static void Main(string[] args)
{
String[] as1 = new String[] { "Static", "with", "initializer" };
ShowArray("as1", as1);
String[] as2 = new String[5];
as2[0] = "Static";
as2[2] = "with";
as2[3] = "initial";
as2[4] = "size";
ShowArray("as2", as2);
ArrayList al3 = new ArrayList();
al3.Add("Dynamic");
al3.Add("using");
al3.Add("ArrayList");
//wow! this is harder than it should be
String[] as3 = (String[])al3.ToArray(typeof(string));
ShowArray("as3", as3);
List<string> gl4 = new List<string>();
gl4.Add("Dynamic");
gl4.Add("using");
gl4.Add("generic");
gl4.Add("list");
//ahhhhhh generic lubberlyness :)
String[] as4 = gl4.ToArray();
ShowArray("as4", as4);
}
private static void ShowArray(string msg, string[] x)
{
Console.WriteLine(msg);
for(int i=0;i<x.Length;i++)
{
Console.WriteLine("item({0})={1}",i,x[i]);
}
}
您可以像其他对象类型一样使用new
运算符:
int[] array = new int[5];
或者,使用变量:
int[] array = new int[someLength];
int[] array = { 1, 2, 3, 4, 5};
for (int i=0;i<=array.Length-1 ;i++ ) {
Console.WriteLine(array[i]);
}
使用泛型列表或ArrayList。