数组读数问题c#

jam*_*uso 1 c# forms windows arrays

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

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

Mat*_*and 5

对于你的直接问题:

错误很简单.你已经声明了变量ascchar,但你实际上没有为它赋予任何东西.你需要类似的东西int[] ascchar = new int[somenumber].或者,如果您不知道您的阵列需要多大(可能tbox_string.Text.Length?),请使用List<int>替代.

但是,如果你的代码旨在为你提供每个字符的ASCII代码,那么你就错了(这不是Convert.ToInt32有效的方法).你可以通过以下方式实现同​​样的目标:

var ascchar = Encoding.ASCIIEncoding.GetBytes(tbox_string.Text);
Run Code Online (Sandbox Code Playgroud)

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