移除不必要的值指派 (IDE0059)

屬性
規則識別碼 IDE0059
標題 移除非必要的值指派
類別 樣式
子類別 不必要的程式碼規則 (運算式層級喜好設定)
適用語言 C# 和 Visual Basic
選項 csharp_style_unused_value_assignment_preference
visual_basic_style_unused_value_assignment_preference

概觀

此規則會標幟不必要的值指派。 例如:

// IDE0059: value written to 'v' is never
// read, so assignment to 'v' is unnecessary.
int v = Compute();
v = Compute2();

您可以採取下列其中一個動作來修正此違規:

  • 如果指派右側的運算式沒有副作用,請移除運算式或整個指派語句。 這可藉由避免不必要的計算來改善效能。

    int v = Compute2();
    
  • 如果指派右側的運算式有副作用,請將指派的左邊取代為 捨棄 (僅限 C#) 或從未使用區域變數。 捨棄可藉由明確顯示捨棄未使用值的意圖來改善程式碼的明確性。

    _ = Compute();
    int v = Compute2();
    

選項。

此選項會指定是否偏好使用捨棄或未使用的區域變數:

如需設定選項的相關資訊,請參閱 選項格式

csharp_style_unused_value_assignment_preference

屬性 數值 Description
選項名稱 csharp_style_unused_value_assignment_preference
適用語言 C#
選項值 discard_variable 在指派未使用的值時,偏好使用捨棄
unused_local_variable 在指派未使用的值時,偏好使用區域變數
預設選項值 discard_variable
// csharp_style_unused_value_assignment_preference = discard_variable
int GetCount(Dictionary<string, int> wordCount, string searchWord)
{
    _ = wordCount.TryGetValue(searchWord, out var count);
    return count;
}

// csharp_style_unused_value_assignment_preference = unused_local_variable
int GetCount(Dictionary<string, int> wordCount, string searchWord)
{
    var unused = wordCount.TryGetValue(searchWord, out var count);
    return count;
}

visual_basic_style_unused_value_assignment_preference

屬性 數值 Description
選項名稱 visual_basic_style_unused_value_assignment_preference
適用語言 Visual Basic
選項值 unused_local_variable 在指派未使用的值時,偏好使用區域變數
預設選項值 unused_local_variable
' visual_basic_style_unused_value_assignment_preference = unused_local_variable
Dim unused = Computation()

隱藏警告

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

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

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

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

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

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

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

屬性
規則識別碼 IDE0059
標題 值未使用
類別 樣式
適用語言 F#
選項

概觀

此規則會標幟不必要的值指派。 例如, answer 下列程式碼片段中未使用 :

type T() =
    let answer = 42

另請參閱