C# で名前付き文字列の書式設定を実現するにはどうすればよいですか?
C# での名前付き文字列の書式設定
Python などのプログラミング言語では、位置ではなく名前で文字列を書式設定できます。たとえば、次のような文字列を指定できます。
print '%(language)s has %(#)03d quote types.' % \ {'language': "Python", "#": 2}
これは、「Python には 002 の引用符タイプがあります。」と表示されます。
C# には、文字列をフォーマットするための組み込みメソッドがありません。名前で。ただし、同様の結果を得る方法はいくつかあります。
辞書の使用
オプションの 1 つは、辞書を使用して変数名をその値にマップすることです。次に、変数名を使用して文字列を書式設定するカスタム文字列書式設定メソッドに辞書を渡すことができます。
例を次に示します。
public static string FormatStringByName(string format, Dictionary<string, object> values) { // Create a regular expression to match variable names in the format string. var regex = new Regex(@"\{(.*?)\}"); // Replace each variable name with its value from the dictionary. var formattedString = regex.Replace(format, match => values[match.Groups[1].Value].ToString()); return formattedString; }
このメソッドは次のように使用できます。
var values = new Dictionary<string, object> { { "some_variable", "hello" }, { "some_other_variable", "world" } }; string formattedString = FormatStringByName("{some_variable}: {some_other_variable}", values);
文字列補間の使用
C# 6.0 以降では、文字列補間を使用して文字列を名前で書式設定できます。文字列補間は、式を文字列に直接埋め込むことができる機能です。
次に例を示します:
string formattedString = $"{some_variable}: {some_other_variable}";
これは、「hello: world」を出力します。
拡張メソッド
もう 1 つのオプションは、拡張メソッドを使用して追加することです名前付き文字列フォーマット機能を文字列クラスに追加します。使用できる拡張メソッドの例を次に示します:
public static class StringExtensions { public static string FormatByName(this string format, object values) { // Get the type of the values object. var type = values.GetType(); // Get the properties of the values object. var properties = type.GetProperties(); // Create a regular expression to match variable names in the format string. var regex = new Regex(@"\{(.*?)\}"); // Replace each variable name with its value from the values object. var formattedString = regex.Replace(format, match => { var property = properties.FirstOrDefault(p => p.Name == match.Groups[1].Value); if (property != null) { return property.GetValue(values).ToString(); } else { return match.Groups[1].Value; } }); return formattedString; } }
この拡張メソッドは次のように使用できます:
string formattedString = "{some_variable}: {some_other_variable}".FormatByName(new { some_variable = "hello", some_other_variable = "world" });
以上がC# で名前付き文字列の書式設定を実現するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











C言語関数によって返される値の種類は何ですか?返品値を決定するものは何ですか?

STL(ソート、検索、変換など)のアルゴリズムを効率的に使用するにはどうすればよいですか?
