共用方式為


CA2017:參數計數不符

屬性
規則識別碼 CA2017
職稱 參數計數不符
類別 可靠性
修正程式是中斷或非中斷 不中斷
在 .NET 10 中預設啟用 作為警告

原因

記錄訊息範本中提供的參數數目不符合具名佔位元元的數目。

檔案描述

此規則旗標會記錄器呼叫的訊息自變數數目不正確。

如何修正違規

比對範本格式的佔位元元數目與傳遞的自變數數目。

隱藏警告的時機

請勿隱藏此規則的警告。

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

另請參閱