다음을 통해 공유


CA2017: 매개 변수 개수 불일치

속성
규칙 ID 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

참고 항목