public bool TryGetCustomerId(out Guid customerId)
{
customerId = Guid.Empty;
if (_contextAccessor.HttpContext?.Request.Headers.TryGetValue(CustomKnownHeaders.CustomerId,
out var values) ?? false)
{
return Guid.TryParse(values.FirstOrDefault(), out customerId);
}
return false;
}
從 .NET Core 3.1 遷移到 .NET 5 后,輸出引數變數顯示錯誤“使用未分配的區域變數”。
錯誤顯示在“值”變數中。錯誤 - “使用未分配的區域變數‘值’”
uj5u.com熱心網友回復:
從 .Net core 3.1 遷移到 .Net 5 后顯示錯誤“Use of unassigned local variable”
我在 netcore3.1 中測驗了類似的東西并得到了同樣的錯誤..
你真的確定代碼在 netcore3.1 中有效嗎?
看起來這是編譯器無法判斷變數已被明確分配的情況之一 - 請參閱此處的“條件訪問合并到 bool 常量” 。您可能需要重寫代碼以幫助解決此問題:
public bool TryGetCustomerId(out Guid customerId)
{
customerId = Guid.Empty;
string[] values = null;
if (_contextAccessor.HttpContext?.Request.Headers.TryGetValue(CustomKnownHeaders.CustomerId,
out values) ?? false)
{
return Guid.TryParse(values.FirstOrDefault(), out customerId);
}
return false;
}
uj5u.com熱心網友回復:
這似乎是編譯器中的錯誤或至少是限制。它顯然沒有意識到這一行:
return Guid.TryParse(values.FirstOrDefault(), out customerId);
永遠不會執行,除非_contextAccessor.HttpContext是非null,TryGetValue被呼叫并被values賦值。
值得注意的是,更改?? false為== true(這是我通常處理這種確切情況的方式)并沒有什么區別。顯然,TryGetValue可能不會被呼叫的事實足以讓編譯器將任何后續使用values視為潛在未分配,即使values不能在使用它的唯一分支中未分配。
除了編譯器中的錯誤之外,很難將其視為其他任何東西,這可能應該在https://github.com/dotnet/roslyn上報告。
編輯 這在 Visual Studio 2022 中似乎不是問題(即使在 .NET5 專案中),因此似乎 MS 確實識別了該錯誤并修復了它。我是用2019打開編譯專案的時候才看到的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/402379.html
標籤:
