我在C#编程,我想定义一个我不知道它的大小的数组,因为我想从文件中读取一些东西,我不知道该文件中的元素数量.这是我的代码,我有"x"数组的问题!
using (TextReader reader = File.OpenText("Numbers.txt")) { string[] bits; string text = reader.ReadLine(); int i ,j=0; int [] x; while (text != null) { i = 0; bits = text.Split(' '); while (bits[i] != null) { x[j] = int.Parse(bits[i]); i++; j++; } text = reader.ReadLine(); } }
之后我会得到这个错误"使用未分配的局部变量'x'"我不知道该怎么办!! 请帮我...
你得到了这个错误,因为你没有初始化变量(你不能真正做到这一点,除非你知道你将存储在其中的项目数量).
由于你不知道项目的数量,你应该使用a List
,它可以根据项目的数量动态扩展:
using (TextReader reader = File.OpenText("Numbers.txt")) { string[] bits; string text = reader.ReadLine(); int i; IList<int> x = new List<int>(); while (text != null) { i = 0; bits = text.Split(' '); while (bits[i] != null) { x.Add(int.Parse(bits[i])); i++; } text = reader.ReadLine(); } }