簡體   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