共用方式為


移除不必要的值指派 (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();
    

選項

這個選項會指定是否偏好使用捨棄或未使用的局部變數:

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

C#_樣式_未使用值指派偏好设置

財產 價值 描述
選項名稱 csharp_樣式_未使用值賦值偏好設定
適用的語言 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
適用的語言 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

另請參閱