分享方式:


CA1854:偏好 IDictionary.TryGetValue(TKey, out TValue) 方法

屬性
規則識別碼 CA1854
標題 IDictionary.TryGetValue(TKey, out TValue)偏好 方法
類別 效能
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 建議

原因

檢查 IDictionaryIDictionary.ContainsKey 保護的專案存取。

檔案描述

存取 的 元素 IDictionary 時,索引子實作會藉由呼叫 IDictionary.ContainsKey 方法來檢查 Null 值。 如果您也會在 子句中 if 呼叫 IDictionary.ContainsKey 來保護值查閱,則只需要一個查閱時,就會執行兩個查閱。

如何修正違規

IDictionary.ContainsKey 調用和專案存取取代為 方法的 IDictionary.TryGetValue 呼叫。

違規

public string? GetValue(string key)
{
    if (_dictionary.ContainsKey(key))
    {
        return _dictionary[key];
    }

    return null;
}
Public Function GetValue(key As String) As String
    If _dictionary.ContainsKey(key) Then
        Return _dictionary(key)
    End If

    Return Nothing
End Function

修正

public string? GetValue(string key)
{
    if (_dictionary.TryGetValue(key, out string? value))
    {
        return value;
    }

    return null;
}
Public Function GetValue(key As String) As String
    Dim value as String

    If _dictionary.TryGetValue(key, value) Then
        Return value
    End If

    Return Nothing
End Function

隱藏警告的時機

如果您使用 的自訂實 IDictionary 作,在執行檢查時 IDictionary.ContainsKey 避免值查閱,則隱藏此警告是安全的。

隱藏警告

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

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

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

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

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