CA1856:ConstantExpected 属性的用法不正确

属性
规则 ID 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) { }

何时禁止显示警告

违反此规则表示代码中存在错误,应始终修复。