共用方式為


在 foreach 循環中新增明確轉換 (IDE0220)

財產 價值
規則標識碼 IDE0220
標題 新增明確轉換
類別 風格
子類別 語言規則 (表示層級的偏好)
適用的語言 C#
選項 dotnet_style_prefer_foreach_explicit_cast_in_source

概述

當編譯器會加入隱式轉型時,此規則會標示出 foreach 迴圈中缺少顯式轉型。 針對泛型或強型別的集合,在編譯程式新增隱藏轉換時強制明確轉換,可能會發現在 foreach 語句中使用不正確的類型。

選項

選項會指定您希望規則強制執行的行為。 如需設定選項的相關資訊,請參閱 選項格式

dotnet_style_prefer_foreach_explicit_cast_in_source

財產 價值 描述
選項名稱 dotnet_style_prefer_foreach_explicit_cast_in_source
選項值 always 偏好在原始碼中使用明確的型別轉換。
when_strongly_typed 偏好強型別 (泛型) 集合的明確轉換,但不適用於舊版集合,例如 ArrayList
預設選項值 when_strongly_typed

// Code with violations.
var list = new List<object>();
foreach (string item in list) { }

// Fixed code.
var list = new List<object>();
foreach (string item in list.Cast<string>())

隱藏警告

如果您想要只隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

#pragma warning disable IDE0220
// The code that's violating the rule is on this line.
#pragma warning restore IDE0220

若要停用檔案、資料夾或項目的規則,請將其嚴重性設定為 組態檔中的 none

[*.{cs,vb}]
dotnet_diagnostic.IDE0220.severity = none

若要停用所有程式碼樣式規則,請將類別 Style 的嚴重性設定為 組態檔中的 none

[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Style.severity = none

如需詳細資訊,請參閱 如何在隱藏程式代碼分析警告。

另請參閱