Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marihachi/06efc655759b376cd2cf to your computer and use it in GitHub Desktop.
Save marihachi/06efc655759b376cd2cf to your computer and use it in GitHub Desktop.

C#でテンプレート的な機能の実現

文字列中に乱数を挿入するなどテンプレート的な機能を実装したい場合がある。

これを実現するのは至って単純で、「<random>」などのトークンをC#のプレースホルダ(書式指定子)である「{0}」に置き換えれば良いというもの。

ただし、「{0}」の0はその置き換える値がString.Formatの第2引数以降の何番目かによって決定される。

以下のプログラムは、テンプレート文字列中のトークンの位置へ乱数(1~10)の挿入を行うものです:

var formatSource = "値は <random> です。";

// トークンをプレースホルダに変換
formatSource = formatSource.Replace("<random>", "{0}");

// テンプレートから乱数を含んだ文字列を生成
var r = new Random();
var str = String.Format(formatSource, r.Next(0, 10) + 1);

// 表示
MessageBox.Show(str);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment