4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

逆文字列置換(reverse string interpolation)

Posted at

参考

この記事は、以下の動画を参考にしています。
詳しくは、動画をご覧ください。

動画で紹介されているNuGetパッケージは、以下のものです。

概要

C#の機能である文字列置換(string interpolation)は、文字列の中に式の値を埋め込む機能です。

var name = "Nick";
var line = $"Hello, {name}!"; // 文字列置換

InterpolatedParserは、文字列置換とは逆向きの、文字列から指定の位置にある値を変数に取り出す機能を提供します。(C# 10のcustom string interpolation handlerを使っています)

using InterpolatedParsing;

var line = "Hello, Nick!";
string name = null;
InterpolatedParser.Parse(line, $"Hello, {name}!"); // nameに"Nick"が入る

警告

このライブラリーは、ランタイムの期待に反する方法でUnsafe.AsRefを悪用しています。 本番コードでこれを使用することは推奨されません。 このライブラリーは、C#の機能や実装の詳細を使って、思いがけない面白いことができるという楽しいちょっとした例として作られたものです。

(READMEの一部をDeepLで翻訳)

追補

OutParserは、InterpolatedPaserと同じ働きをする、同じ作者による別のパッケージです。

using OutParsing;

var line = "Hello, Nick!";
OutParser.Parse(line, "Hello, {name}!", out string name); // nameに"Nick"が入る

OutParserを使用するにあたり、現時点のバージョン(1.0.1)では、以下の制限があります。

  • .NET 9のインターセプターを使っています
  • プロジェクトファイル(*.csproj)に、以下のInterceptorsNamespaces要素を追加する必要があります
<Project Sdk="...">

  <PropertyGroup>
    <!-- 略 -->
    <TargetFramework>net9.0</TargetFramework>
    <InterceptorsNamespaces>$(InterceptorsNamespaces);OutParsing</InterceptorsNamespaces>
  </PropertyGroup>
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?