问题
I noticed that ReSharper suggests me to check Console.ReadLine()
for null. I don't understand why, because as far as I know the method returns ""
even if you press enter
in a console and don't enter any symbol.
I use VS 2015 with the 3rd update, C# 6, .NET 4.6.1, ReSharper 10.
回答1:
The documentation specifies that returning null is part of the contract for this method:
The next line of characters from the input stream, or null if no more lines are available.
And goes onto give an example:
If the Ctrl+Z character is pressed when the method is reading input from the console, the method returns null.
As a further example, you can change the TextReader
used for Console.In
using Console.SetIn
. Your TextReader
could return null when ReadLine
is called.
回答2:
Console.ReadLine()
can be null
if you enter Ctrl + Z.
MSDN documentation:
If the Ctrl+Z character is pressed when the method is reading input from the console, the method returns null. This enables the user to prevent further keyboard input when the ReadLine method is called in a loop.
回答3:
According to MSDN, if you have redirected standard input to be from a file, Console.ReadLine()
will return null
when there are no lines remaining to be read from the file.
来源:https://stackoverflow.com/questions/38370565/resharper-says-that-console-readline-returns-null-value