Skip to content

Instantly share code, notes, and snippets.

@huanlin
Last active April 21, 2022 11:44
Show Gist options
  • Save huanlin/d03f67a9663c21baf716187371f2280c to your computer and use it in GitHub Desktop.
Save huanlin/d03f67a9663c21baf716187371f2280c to your computer and use it in GitHub Desktop.
using System.Runtime.CompilerServices;
......
[InterpolatedStringHandler]
public ref struct MyLoggerInterpolatedStringHandler
{
private DefaultInterpolatedStringHandler _handler;
public MyLoggerInterpolatedStringHandler(
int literalLength, int formattedCount,
MyLogger logger, out bool handlerIsValid)
{
if (!logger.Enabled)
{
_innerHandler = default;
handlerIsValid = false;
return;
}
_handler = new DefaultInterpolatedStringHandler(literalLength, formattedCount);
handlerIsValid = true;
}
public void AppendLiteral(string msg)
{
_handler.AppendLiteral(msg);
}
public void AppendFormatted<T>(T msg)
{
_handler.AppendFormatted(msg);
}
public string ToStringAndClear()
{
return _handler.ToStringAndClear();
}
}
var date = DateTime.Now;
logger.Enabled = true; // 啟用記錄功能
logger.Log($"今天是 {date.Month} 月 {date.Day} 日");
logger.Enabled = false; // 關閉記錄功能
logger.Log($"今天是 {date.Month} 月 {date.Day} 日");
public class MyLogger
{
public bool Enabled { get; set; }
public void Log(
[InterpolatedStringHandlerArgument("")]
ref MyLoggerInterpolatedStringHandler handler)
{
if (Enabled)
{
string msg = handler.ToStringAndClear();
Console.WriteLine(msg);
}
}
}
public static class MyLoggerExtension
{
public static void Log(
this MyLogger logger,
[InterpolatedStringHandlerArgument("logger")]
ref MyLoggerInterpolatedStringHandler handler)
{
......
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment