我知道这是一个简单的问题,但它一直困扰着我一整天。我尝试通过方法(setLength)中的变量设置数组的长度。但是在我调用方法setLength
之后,我的数组的长度仍为0,当我调用方法setLength
时,它是否设置为5?
C#代码段:
class myProject
{
public static int length = 0;
public static string[] myArray1 = new string[length];
public static string[] myArray2 = new string[length];
public static void setLength()
{
length = 5;
}
public static void process()
{
setLength();
for(int i=0; i<length; i++)
{
.....code for my array
}
}
答案 0 :(得分:6)
您必须创建一个新数组。
public static void setLength()
{
length = 5;
myArray1 = new string[length];
}
您不能随意改变长度。 c#数组不支持。
如果您想使用可变长度结构,我建议您使用List<string>
答案 1 :(得分:5)
在构造对象时,使用长度变量的值设置数组的大小。在数组中没有创建变量关系:大小设置一次并在此后修复。
如果您想要一个更改大小的数组,请使用List&lt; string&gt;等集合类型。
答案 2 :(得分:2)
由于myArray1
和myArray2
的长度均为length
,其中length
等于0
,因此其长度始终为{{1}除非你改变它,因为IDE逐行编译项目。
但是,如果您愿意更改数组长度,可以使用0
,其中Array.Resize<T>(ref T[] array, int newSize)
是要调整大小的数组,array
是数组的新长度。
示例强>
newSize
注意:在大多数情况下,最好使用class myProject
{
public static int length = 0; //Initialize a new int of name length as 0
public static string[] myArray1 = new string[length]; //Initialize a new array of type string of name myArray1 as a new string array of length 0
public static string[] myArray2 = new string[length]; //Initialize a new array of type string of name myArray2 as a new string array of length 0
public static void setLength()
{
length = 5; //Set length to 5
}
public static void process()
{
setLength(); //Set length to 5
Array.Resize(ref myArray1, length); //Sets myArray1 length to 5
//Debug.WriteLine(myArray1.Length.ToString()); //Writes 5
}
,因为它更易于管理和动态调整大小。
示例强>
System.Collections.Generic.List<T>
谢谢, 我希望你觉得这很有帮助:)
答案 3 :(得分:1)
您应该做的不是在Class声明中初始化数组的大小,而是在setLength方法中初始化它。之前的答案陈述的问题是,一旦初始化数组,调整它的大小是一项昂贵的操作。如果您不止一次这样做,则需要考虑使用List<string>
。
class myProject
{
public static int length = 0;
public static string[] myArray1;
public static string[] myArray2;
public static void setLength(int value)
{
myArray1 = new string[value];
myArray2 = new string[value];
}
public static void process()
{
length = 5;
setLength(length);
for(int i=0; i<length; i++)
{
.....code for my array
}
}
}