簡體   English   中英

c# 中的警告是否可以,或者我應該做些什么?

[英]Is it okay warnings in c# or should I do something?

我的代碼工作正常,但每次運行代碼時,我都會收到我無法理解的警告。 我在我的 linux 終端中運行代碼,它說: Converting null literal or possible null value to non-nullable type Is it normal? 或者我應該做些什么? 這是我的代碼:

namespace test2;
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Choose option: \n1. +\n2. -\n3. *\n4. /");
        int num = Convert.ToInt32(Console.ReadLine());
        string ext = Console.ReadLine();
        if(num == 1){
            while(true){
                Console.WriteLine("Enter numbers or tap Q to exit:");
            int x = Convert.ToInt32(Console.ReadLine());
            int y = Convert.ToInt32(Console.ReadLine());
            int z = x + y;
            Console.WriteLine("{0}+{1}={2}", x,y,z);
            if(ext =="Q"){
                break;
            }
        }
        }
    }
}

我試圖在 while 循環中寫 ext 但我不能

警告是告訴您右側表達式可能返回空值,在您的情況下,變量的左側不可為空。

參考Console.ReadLine的聲明,它返回string? .

所以你可以像string? ext = Console.ReadLine(); string? ext = Console.ReadLine(); 擺脫這個警告。

您可以定義一個默認為 null 的變量,例如

int? num = Convert.ToInt32(Console.ReadLine());

該警告與將可空類型分配給不可空類型有關。 一個簡單的替代方法是使用int.tryparse()方法,如下所示:

int num;
int.TryParse(Console.ReadLine(),out num);

嘗試用int.Parse替換Convert.ToInt32

這就是我為修復你的代碼所做的一點我把條件放在 while 循環中而且你忘記在每次迭代后更新 ext 另外我改變了將 int 輸入的方法改為 int.Parse 而不是你的 Convert。到 Int32。 試試這個,我相信它會按預期工作。

Console.WriteLine("Choose option: \n1. +\n2. -\n3. *\n4. /");
        int num = Convert.ToInt32(Console.ReadLine());
        if (num == 1)
        {
            string ext = Console.ReadLine();
            while (!ext.Equals("Q"))
            {
                Console.WriteLine("Enter numbers or tap Q to exit:");
                int x = int.Parse(Console.ReadLine());
                int y = int.Parse(Console.ReadLine());
                int z = x + y;
                Console.WriteLine("{0}+{1}={2}", x, y, z);
                ext = Console.ReadLine();
            }

        }

暫無
暫無

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

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