Anteckning
Åtkomst till den här sidan kräver auktorisering. Du kan prova att logga in eller ändra kataloger.
Åtkomst till den här sidan kräver auktorisering. Du kan prova att ändra kataloger.
| Property | Värde | 
|---|---|
| Regel-ID | CA2017 | 
| Title | Matchningsfel för antal parametrar | 
| Kategori | Tillförlitlighet | 
| Korrigeringen är icke-bakåtkompatibel | Icke-icke-bryta | 
| Aktiverad som standard i .NET 9 | Som varning | 
Orsak
Antalet parametrar som anges i mallen för loggningsmeddelande matchar inte antalet namngivna platshållare.
Regelbeskrivning
Den här regeln flaggar loggningsanrop som har ett felaktigt antal meddelandeargument.
Så här åtgärdar du överträdelser
Matcha antalet platshållare i mallformatet med antalet skickade argument.
När du ska ignorera varningar
Ignorera inte en varning från den här regeln.
Example
I följande exempel visas metoder som bryter mot CA2017 och metoder som uppfyller regeln.
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