CA2017:参数计数不匹配

属性
规则 ID CA2017
标题 参数计数不匹配
类别 可靠性
修复是中断修复还是非中断修复 非中断
在 .NET 9 中默认启用 作为警告

原因

日志记录消息模板中所提供参数的数量与已命名占位符的数量不匹配。

规则说明

此规则标记具有错误数目的消息参数的记录器调用。

如何解决冲突

将模板格式中的占位符数与传递的参数数匹配。

何时禁止显示警告

不禁止显示此规则发出的警告。

Example

以下示例显示了违反 CA2017 的方法和满足规则的方法。

public class LoggingExample
{
    private readonly ILogger<LoggingExample> _logger;

    public LoggingExample(ILogger<LoggingExample> logger)
    {
        _logger = logger;
    }

    public void ExampleMethod()
    {
        string name = "Alice";
        int age = 30;

        // Violates CA2017: Too few arguments for placeholders.
        _logger.LogInformation("User {Name} is {Age} years old and lives in {City}", name, age);

        // Violates CA2017: Too many arguments for placeholders.
        _logger.LogError("Error occurred: {Message}", "Something went wrong", "Extra argument");

        // Correct usage: Matching number of placeholders and arguments.
        _logger.LogInformation("User {Name} is {Age} years old", name, age);
    }
}
Imports Microsoft.Extensions.Logging

Public Class LoggingExample

    Private ReadOnly _logger As ILogger(Of LoggingExample)

    Public Sub New(logger As ILogger(Of LoggingExample))
        _logger = logger
    End Sub

    Public Sub ExampleMethod()
        Dim name As String = "Alice"
        Dim age As Integer = 30

        ' Violates CA2017: Too few arguments for placeholders.
        _logger.LogInformation("User {Name} is {Age} years old and lives in {City}", name, age)

        ' Violates CA2017: Too many arguments for placeholders.
        _logger.LogError("Error occurred: {Message}", "Something went wrong", "Extra argument")

        ' Correct usage: Matching number of placeholders and arguments.
        _logger.LogInformation("User {Name} is {Age} years old", name, age)
    End Sub

End Class

另请参阅