| 屬性 | 值 |
|---|---|
| 規則識別碼 | CA2017 |
| 職稱 | 參數計數不符 |
| 類別 | 可靠性 |
| 修正是造成中斷還是不中斷 | 不中斷 |
| 在 .NET 10 中預設啟用 | 作為警告 |
| 適用語言 | C# 與 Visual Basic |
原因
記錄訊息模板中提供的參數數目不符合具名佔位符的數目。
規則描述
此規則標記訊息參數數量不正確的日誌記錄器呼叫。
如何修正違規
比對模板中的佔位符數量與所傳遞參數的數量。
隱藏警告的時機
請勿隱藏此規則的警告。
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