Last active
August 11, 2021 10:50
-
-
Save asmichi/3267486211f70b5a71a3f9ea33e1ce86 to your computer and use it in GitHub Desktop.
Improved Interpolated Strings を濫用して、 string 以外の結果を生成してみる
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Improved Interpolated Strings を濫用して、 string 以外の結果を生成してみる。 | |
using System.Runtime.CompilerServices; | |
using System.Text; | |
/* | |
args[0] = C:\Program Files\dotnet\dotnet.exe | |
args[1] = build | |
args[2] = Sugoi App\Sugoi App.sln | |
args[3] = --nologo | |
args[4] = --verbosity | |
args[5] = quiet | |
*/ | |
var dotnetExe = @"C:\Program Files\dotnet\dotnet.exe"; | |
var sln = @"Sugoi App\Sugoi App.sln"; | |
var ss = SplitBySpace($"{dotnetExe} build {sln} --nologo --verbosity quiet"); | |
for (int i = 0; i < ss.Length; i++) | |
{ | |
Console.WriteLine("args[{0}] = {1}", i, ss[i]); | |
} | |
// リテラル部分の空白文字で分割した配列を生成する。フォーマット部分の空白文字では分割しない。 | |
static string[] SplitBySpace([InterpolatedStringHandlerArgument] in SplitBySpaceHandler handler) => | |
handler.ToStringsAndClear(); | |
// 実装はクソ | |
[InterpolatedStringHandler] | |
public struct SplitBySpaceHandler | |
{ | |
private readonly List<string> _strings; | |
private readonly StringBuilder _currentStringBuilder; | |
public SplitBySpaceHandler( | |
int literalLength, | |
int formattedCount) | |
{ | |
_strings = new(); | |
_currentStringBuilder = new(); | |
} | |
public void AppendLiteral(string s) | |
{ | |
foreach (var c in s) | |
{ | |
if (c == ' ') | |
{ | |
FinishCurrentString(); | |
} | |
else | |
{ | |
_currentStringBuilder.Append(c); | |
} | |
} | |
} | |
public void AppendFormatted<T>(T t) | |
{ | |
_currentStringBuilder.Append(t?.ToString()); | |
} | |
public string[] ToStringsAndClear() | |
{ | |
FinishCurrentString(); | |
var strings = _strings.ToArray(); | |
_strings.Clear(); | |
return strings; | |
} | |
private void FinishCurrentString() | |
{ | |
if (_currentStringBuilder.Length != 0) | |
{ | |
_strings.Add(_currentStringBuilder.ToString()); | |
_currentStringBuilder.Clear(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment