繁体   English   中英

将字符串转换为Char数组时出现NullReference异常

[英]NullReference Exception in converting string to Char array

Null Reference Exception on line char[] myChar = read.ToCharArray();显示Null Reference Exception on line char[] myChar = read.ToCharArray();

我不知道。 请帮忙

class Program
{
    static void Main(string[] args)
    {
        StreamReader myReader = new StreamReader("TextFile1.txt");
        string read = "";

        while (read != null)
        {
            read = myReader.ReadLine();
            Console.WriteLine(read);

        }

       char[] myChar = read.ToCharArray();

        for (int i = 0; i < myChar.Length; i++)
        {
            Console.WriteLine(myChar[i]);
        }

        Console.WriteLine(read);
        myReader.Close();
        Console.ReadKey();
    }
}

循环结束后, read应为null ,并且在null上调用ToCharArray应该会产生异常。 您可以将此语句放入while循环中。 我相信您正在尝试做一些实验,因为已经使用Console.WriteLine(read);打印了字符串Console.WriteLine(read);

while ((read = sr.ReadLine()) != null)
{      
    Console.WriteLine(read);
    char[] myChar = read.ToCharArray();
    for (int i = 0; i < myChar.Length; i++)        
        Console.WriteLine(myChar[i]);       
}
        StringBuilder sb = new StringBuilder();
        using (StreamReader sr = new StreamReader("TestFile.txt")) 
        {
            string line;
            // Read and display lines from the file until the end of 
            // the file is reached.
            while ((line = sr.ReadLine()) != null) 
            {
                Console.WriteLine(line);
                sb.Append(line);
            }
        }

        var chars = sb.ToString().ToCharArray();

但是,您应该将每一行添加到stringbuilder中,然后将其转换为char数组。 事情就是您真正想做的吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM