| 资产 | 价值 |
|---|---|
| 规则 ID | CA2023 |
| 标题 | 消息模板中的大括号无效 |
| 类别 | Reliability |
| 修复是中断修复还是非中断修复 | Non-breaking |
| 在 .NET 10 中默认启用 | 作为警告 |
原因
消息模板中存在的大括号无效。 确保邮件模板中的任何大括号都是有效的左大括号/右大括号,或进行转义。
规则说明
记录消息模板使用大括号 { 并 } 表示值的命名占位符。 消息模板中的大括号用法无效可能会导致运行时异常或意外的日志记录行为。 此规则检测:
- 不匹配的左大括号或右大括号。
- 未正确转义的嵌套大括号。
- 其他格式不正确的大括号模式。
如何修复违规行为
若有解决此规则的冲突:
- 确保所有左大括号
{都有相应的右大括号}。 - 通过加倍转义文本大括号:
{{for{和}}for}. - 修复任何嵌套或格式不正确的大括号模式。
Example
以下代码片段显示了 CA2023 的冲突:
using Microsoft.Extensions.Logging;
class Example
{
private readonly ILogger _logger;
public Example(ILogger<Example> logger)
{
_logger = logger;
}
public void LogData(string name, int value)
{
// Violation: unmatched opening brace.
_logger.LogInformation("Processing {Name with value {Value}", name, value);
// Violation: unmatched closing brace.
_logger.LogInformation("Processing Name} with value {Value}", name, value);
}
}
Imports Microsoft.Extensions.Logging
Class Example
Private ReadOnly _logger As ILogger
Public Sub New(logger As ILogger(Of Example))
_logger = logger
End Sub
Public Sub LogData(name As String, value As Integer)
' Violation: unmatched opening brace.
_logger.LogInformation("Processing {Name with value {Value}", name, value)
' Violation: unmatched closing brace.
_logger.LogInformation("Processing Name} with value {Value}", name, value)
End Sub
End Class
以下代码片段修复了冲突:
using Microsoft.Extensions.Logging;
class Example
{
private readonly ILogger _logger;
public Example(ILogger<Example> logger)
{
_logger = logger;
}
public void LogData(string name, int value)
{
// Fixed: proper braces.
_logger.LogInformation("Processing {Name} with value {Value}", name, value);
// Fixed: escaped literal braces.
_logger.LogInformation("Processing {{Name}} with value {Value}", name, value);
}
}
Imports Microsoft.Extensions.Logging
Class Example
Private ReadOnly _logger As ILogger
Public Sub New(logger As ILogger(Of Example))
_logger = logger
End Sub
Public Sub LogData(name As String, value As Integer)
' Fixed: proper braces.
_logger.LogInformation("Processing {Name} with value {Value}", name, value)
' Fixed: escaped literal braces.
_logger.LogInformation("Processing {{Name}} with value {Value}", name, value)
End Sub
End Class
何时禁止显示警告
不要禁止显示此规则的警告。 消息模板中的大括号无效可能会导致运行时异常或日志输出不正确。
禁止显示警告
如果只想抑制单个冲突,请将预处理器指令添加到源文件以禁用该规则,然后重新启用该规则。
#pragma warning disable CA2023
// The code that's violating the rule is on this line.
#pragma warning restore CA2023
若要禁用文件、文件夹或项目的规则,请在none中将其严重性设置为。
[*.{cs,vb}]
dotnet_diagnostic.CA2023.severity = none
有关详细信息,请参阅 如何禁止显示代码分析警告。