簡體   English   中英

Console.ReadLine() 顯示“將 null 文字或可能的 null 值轉換為不可空類型。”

[英]Console.ReadLine() showing "Converting null literal or possible null value to non-nullable type."

C# 的新手。我正在嘗試這段代碼,它是我從 w3school 用戶輸入中復制的

using System;
 
namespace Sample
{
    class Test
    {
        public static void Main(string[] args)
        {
            string testString;
            Console.Write("Enter a string - ");
            testString = Console.ReadLine();
            Console.WriteLine("You entered '{0}'", testString);
        }
    }
}

但是在我執行該程序后,它在Console.ReadLine()處顯示錯誤;

將 null 文字或可能的 null 值轉換為不可空類型。

您需要處理可為空的嘗試替換

string testString;

string? testString = null;

或者

string testString="";

在 testString 的聲明中,注意 ? 在數據類型之后添加的符號。 這表明該變量可以具有 null 值,這意味着它可以為空。

在 .NET 的最新版本中,默認支持可空引用類型,Console.ReadLine 返回可空字符串。 這意味着您需要將變量聲明為可為空:

string? testString;

或者指定返回值一定不會是null:

testString = Console.ReadLine()!;

如果您使用前者,您將在以后使用該變量時考慮到這一點。 后者是可以的,因為在控制台 window 中,它永遠不會是 null。

您應該閱讀一些關於可空引用類型的內容。

您需要確保您有一個有效的非空string

例如,您可以這樣做以確保在使用格式化程序將其打印到控制台之前它是有效的:

testString = Console.ReadLine() ?? string.Empty;

這將為testString變量分配一個空string ,以防ReadLine()返回null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM