代码检查:传递字符串插值表达式
C# 6.0 引入的字符串插值表达式功能的最大缺点之一是无法高效地延迟字符串格式化并将其委托给插值字符串表达式的使用者。 这在允许 在运行时更改日志级别的日志框架中非常重要,因为当日志记录被禁用时,您不希望在频繁的日志调用上浪费资源:
// works fast if the VERBOSE level is disabled
Logger.Verbose("info = {0}", objectWithSlowToString);
// always invokes 'objectWithSlowToString.ToString()', slow
Logger.Verbose($"info = {objectWithSlowToString}");
C# 10 通过引入 插值字符串处理程序的概念解决了这个问题。 对于最终用户,这意味着字符串插值表达式在 .NET 6 中通常运行得更快,并允许在插值孔中使用 Span<char> 值。 对于库作者,此功能允许控制字符串插值表达式是否被转换为字符串。
JetBrains Rider 识别库代码中的“插值字符串处理程序”模式,并建议在可能的情况下使用字符串插值表达式:
public static class LoggerTest
{
public static void Test(String[] args)
{
// Pass string interpolation expression
Logger.Log("length = {0}", args.Length);
}
}
public static class LoggerTest
{
public static void Test(String[] args)
{
Logger.Log($"length = {args.Length}");
}
}
public static class Logger
{
[StringFormatMethod("format")]
public static void Log(string format, params object[] args)
{
// write to file
}
public static void Log(ref CustomInterpolatedStringHandler handler)
{
// write to file
}
[InterpolatedStringHandler]
public readonly struct CustomInterpolatedStringHandler
{
private readonly StringBuilder? _builder;
public CustomInterpolatedStringHandler(int literalLength, int formattedCount, out bool shouldAppend)
{
_builder = new StringBuilder(capacity: literalLength + formattedCount * 11);
shouldAppend = true;
}
public void AppendLiteral(string value) => _builder?.Append(value);
public void AppendFormatted<T>(T value) => _builder?.Append(value);
public void AppendFormatted(string? value) => _builder?.Append(value);
public override string? ToString() => _builder?.ToString();
}
}
最后修改日期: 2025年 9月 26日