次の方法で共有


CA2017: パラメーター カウントが一致しません

プロパティ
ルール ID CA2017
Title パラメーター カウントが一致しません
[カテゴリ] 信頼性
修正が中断ありか中断なしか なし
.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

関連項目