我正在撰寫一個具有一些基本功能的控制臺應用程式,讓用戶輸入并根據用戶輸入做出反應。在以前的(.net 3.1)中,我可以做這樣的事情:
string str=Console.ReadLine();
if(str==""){
Console.WriteLine("do this");
}
else {
Console.WriteLine("do that");
}
由于這是一個新的作業系統,我只是嘗試安裝 .net-6.0 而不用考慮太多。但是,由于 .net-6.0 中的一些更新,Console.ReadLine() 的回傳型別現在是字串?這是可為空的,代碼將如下所示:
string? str=Console.ReadLine();
if(str==""){
Console.WriteLine("do this");
}
else {
Console.WriteLine("do that");
}
因為我想從用戶那里獲得輸入,所以我可以忽略這里的警告以使用與 .net3.1 相同的編碼,是否會 string? str=Console.ReadLine()為 null 并導致 nullreference 例外。或者是什么原因我可以從 Console.ReadLine(); 生成 null
uj5u.com熱心網友回復:
Console.ReadLine()回傳null當輸入從管道到來/重定向STDIN(而不是互動式控制臺),并且重定向流到達末尾; 因此,Console.ReadLine() 可以回傳null,并且總是可以。
您所看到的是 ac# 8 特性:可為空的參考型別 -string?簡單地將其形式化為“我們預期為空的字串參考”,而不是string“不應為空的字串參考”。這里的關鍵點是:回傳值沒有改變——簡單地說:編譯器現在認識到這null是一種你應該考慮的可能性。
以下程式將接受一個管道輸入,將其讀到最后,并寫入找到的行數:
int count = 0;
while (Console.ReadLine() is not null) count ;
Console.WriteLine(count);
使用時,例如(來自cmd):
MyExe < somefile
但是,當在互動式終端中使用時:它永遠不會結束,直到你用ctrl 硬殺死它c
uj5u.com熱心網友回復:
根據 的檔案Console.ReadLine,該方法僅null在沒有更多輸入時才回傳:
輸入流中的下一行字符,如果沒有更多行可用,則為 null。
盡管如此,null無論如何檢查一下是很好的:
string? str=Console.ReadLine();
if (string.IsNullOrEmpty(str))
{
Console.WriteLine("do this");
}
else
{
Console.WriteLine("do that");
}
或者,如果您絕對確定不會為空,請使用 ! (null-forgiving) operator
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/376372.html
下一篇:如何將物件從動作轉換為視圖
