CA1857:该参数需要常量以获得最佳性能

属性
规则 ID CA1857
标题 该参数需要一个常量来获得最佳性能
类别 “性能”
修复是中断修复还是非中断修复 非中断
在 .NET 8 中默认启用 作为警告

原因

向通过 ConstantExpectedAttribute 注释的参数传递了无效的自变量。

规则说明

此规则标记代码中的以下位置:

如何解决冲突

请更正代码,如收到的特定错误消息所示。

示例 1(预期属性)

以下代码片段演示了 CA1857 冲突:

public interface I1<T>
{
    T M1(T operand1, [ConstantExpected] T operand2);
}

public class C1 : I1<int>
{
    public int M1(int operand1, int operand2) =>
        throw new NotImplementedException();
}

以下代码片段修复了冲突:

public interface I1<T>
{
    T M1(T operand1, [ConstantExpected] T operand2);
}

public class C1 : I1<int>
{
    public int M1(int operand1, [ConstantExpected] int operand2) =>
        throw new NotImplementedException();
}

示例 2(常量非常量)

以下代码片段演示了 CA1857 冲突:

static void M1(int i) => M2(i);
static void M2([ConstantExpected] int i) { }

以下代码片段修复了冲突:

static void M1([ConstantExpected] int i) => M2(i);
static void M2([ConstantExpected] int i) { }

示例 3(无效常量)

以下代码片段演示了 CA1857 冲突:

static void M1() => M2((string)(object)20);
static void M2([ConstantExpected] string s) { }

以下代码片段修复了冲突:

static void M1() => M2("20");
static void M2([ConstantExpected] string s) { }

示例 4(常量超出边界)

以下代码片段演示了 CA1857 冲突:

static void M1() => M2(5);
static void M2([ConstantExpected(Min = 3, Max = 4)] int i) { }

以下代码片段修复了冲突:

static void M1() => M2(4);
static void M2([ConstantExpected(Min = 3, Max = 4)] int i) { }

何时禁止显示警告

如果性能不是问题,可禁止显示此规则的警告。

抑制警告

如果只想抑制单个冲突,请将预处理器指令添加到源文件以禁用该规则,然后重新启用该规则。

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

若要对文件、文件夹或项目禁用该规则,请在配置文件中将其严重性设置为 none

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

有关详细信息,请参阅如何禁止显示代码分析警告