【问题标题】:Array reading problems c#数组读取问题c#
【发布时间】:2016-09-13 22:27:33
【问题描述】:

我得到这个代码来存储一些数字到一个特定的数组,但是 IDE 显示这个错误“使用未分配的局部变量 'ascchar'”。

    private void strtoasc()
    {
        int[] ascchar;
        int i = 0;
        foreach (char stg in tbox_string.Text)
        {
            ascchar[i] = Convert.ToInt32(stg);
            i++;
        }
    }

【问题讨论】:

    标签: c# arrays windows forms


    【解决方案1】:

    您应该在为其赋值之前设置数组边界,如果您像这样(int[] someArray=new int[somepositiveInt])初始化一个数组,它将创建一个具有指定数量索引的数组(所有索引都有0)。然后您可以为每个索引分配值。

    private void strtoasc()
    {
        int[] ascchar=new int[tbox_string.Text.Length];// It will solve the issue
        int i = 0;
        foreach (char stg in tbox_string.Text)
        {
            ascchar[i] = Convert.ToInt32(stg);
            i++;
        }
    }
    

    或者,您将使用以下命令获得相同的输出:

     int[] ascchar=tbox_string.Text.Select(c => (int)(c - '0')).ToArray();
    

    【讨论】:

      【解决方案2】:

      为您解决眼前的问题:

      错误非常简单。您已经声明了变量ascchar,但实际上并没有给它分配任何东西。你需要像int[] ascchar = new int[somenumber] 这样的东西。或者,如果您不知道数组需要多大(可能是tbox_string.Text.Length?),请改用List<int>

      但是,如果您的代码旨在为您返回每个字符的 ASCII 代码,那么您就错了(Convert.ToInt32 不是这样工作的)。您可以通过以下方式实现相同的目标:

      var ascchar = Encoding.ASCIIEncoding.GetBytes(tbox_string.Text);
      

      https://msdn.microsoft.com/en-us/library/system.text.asciiencoding(v=vs.110).aspx

      【讨论】:

      • 哦,谢谢,但我只需要 ASCII 数字和 Convert.ToInt32 给我。
      • GetBytes 为您提供。一气呵成。如果是 ASCII,它们真的应该是 bytes 而不是 int
      • @jamescaruso Convert.ToInt32(Char) 将作为Char 的UTF-16 代码单元“转换”为作为int 的UTF-16 代码单元。
      猜你喜欢
      • 2015-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      • 2013-05-25
      相关资源
      最近更新 更多