c#中未知大小的数组

 mobiledu2502861407 发布于 2023-02-09 13:02

我在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'"我不知道该怎么办!! 请帮我...

1 个回答
  • 你得到了这个错误,因为你没有初始化变量(你不能真正做到这一点,除非你知道你将存储在其中的项目数量).

    由于你不知道项目的数量,你应该使用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();
       }
    }
    

    2023-02-09 13:03 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有