在這種情況下,我似乎無法理解編譯器的警告:
using System;
using System.Collections.Generic;
#nullable enable
public class Program
{
public static void Main()
{
Guid guid = Guid.NewGuid();
Dictionary<Guid, string> d = new();
bool found = d.TryGetValue(guid, out string? str);
if (found is false)
{
return;
}
string s = str; // WARNING: possible null value
}
}
畢竟,found如果沒有值(例如,當out str值為空時),我會進行檢查并回傳。另外,方法的out引數用.TryGetValue注釋[MaybeNullWhen(false)]。
感謝您幫助我們找出我的期望錯在哪里并修復代碼,謝謝。代碼在這里。
uj5u.com熱心網友回復:
基本上,編譯器(或語言規范)不夠“智能”,無法TryGetValue在使用區域變數時對回傳值進行條件處理。
如果您將TryGetValue呼叫行內到if條件中,那很好:
if (!d.TryGetValue(guid, out string? str))
{
return;
}
string s = str; // No warning
隨著時間的推移,這可能會變得更加復雜,但是以防彈的方式指定這類事情相對困難。
這不僅限于可為空的參考型別——在其他情況下,從人類的角度來看,邏輯代碼是可以的,但編譯器會拒絕它。例如:
string text;
bool condition = DateTime.UtcNow.Hour == 5;
if (condition)
{
text = "hello";
}
if (condition)
{
Console.WriteLine(text); // Error: use of unassigned local variable
}
我們知道,如果我們進入第二個if陳述句體,我們也會進入第一個陳述句體,因此text會被賦值,但是編譯器的規則并沒有試圖足夠聰明地發現它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/420911.html
標籤:
