rksoftware

Visual Studio とか C# とかが好きです

補間された文字列の改善

■ C# 10.0 での新機能

・補間された文字列の改善 (ImprovedInterpolatedStrings)
  https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-10.0/improved-interpolated-strings
 ロギングフレームワークなどを想定した文字列補完の効率化。
 そのための属性が追加された。 System.Runtime.CompilerServices.InterpolatedStringHandlerAttribute

A a = new();

a.Method($"{"Test"}");
a.Method($"a{1}b{2}c");
a.Method($"{DateTime.Now}");
/*
コンソールには次の出力
s
AppendLitera a
AppendFormatted System.Int32
AppendLitera b
AppendFormatted System.Int32
AppendLitera c
p
AppendFormatted System.DateTime
p
*/

class A
{
    public void Method(string s) { Console.WriteLine("s"); }
    public void Method(SampleHandler p) { Console.WriteLine("p"); }
}

[System.Runtime.CompilerServices.InterpolatedStringHandler]
public ref struct SampleHandler
{
    public SampleHandler(int literalLength, int formattedCount, out bool handlerIsValid) => handlerIsValid = true;
    public void AppendLiteral(string s) => Console.WriteLine($"AppendLitera {s}");
    public void AppendFormatted<T>(T t) => Console.WriteLine($"AppendFormatted {t.GetType().FullName}");
}