CA1856:ConstantExpected 屬性的使用方式不正確

屬性
規則識別碼 CA1856
標題 ConstantExpected 屬性的使用方式不正確
類別 效能
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 錯誤

原因

屬性 ConstantExpectedAttribute 未正確套用至參數。

檔案描述

此規則旗標會不正確使用 ConstantExpectedAttribute 屬性,例如:

如何修正違規

更正您的程式碼,如您收到的特定錯誤訊息所指示。

範例

下列程式碼片段顯示 CA1856 的違規:

using System.Diagnostics.CodeAnalysis;

// Violation - value not compatible with parameter type.
static void M1([ConstantExpected(Min = "a")] char val) { }
// Violation - unsupported type for attribute.
static void M2([ConstantExpected] decimal val) { }
// Violation - Min and Max values are inverted.
static void M3([ConstantExpected(Max = 0, Min = 1)] int val) { }
// Violation - value does not fit within the parameter value bounds.
static void M4([ConstantExpected(Min = long.MinValue)] int val) { }

下列程式碼片段會修正違規:

using System.Diagnostics.CodeAnalysis;

static void M1([ConstantExpected(Min = 'a')] char val) { }
static void M2(decimal val) { }
static void M3([ConstantExpected(Min = 0, Max = 1)] int val) { }
static void M4([ConstantExpected(Min = int.MinValue)] int val) { }

隱藏警告的時機

違反此規則表示程式碼中有錯誤,而且應該一律修正。