LoginSignup
5
3

More than 3 years have passed since last update.

C#の文字列補完 $"{}" でInvariantCultureを強制する方法

Posted at

結論から先に書くと、FormattableString.Invariant(FormattableString) Method を使いましょう。

var now = DateTime.UtcNow;
var val = 12345.6789;
Console.WriteLine($"CurrentCulture  : {now}, {val:N}");
Console.WriteLine(FormattableString.Invariant($"InvariantCulture: {now}, {val:N}"));
FormattableString fmtString = $"{now}, {val:N}";
Console.WriteLine("CurrentCulture  : " + fmtString.ToString(System.Globalization.CultureInfo.CurrentCulture));
Console.WriteLine("InvariantCulture: " + fmtString.ToString(System.Globalization.CultureInfo.InvariantCulture));
Console.WriteLine("fr-FR-Culture   : " + fmtString.ToString(System.Globalization.CultureInfo.GetCultureInfo("fr-FR")));

/* result output
CurrentCulture  : 2021/05/12 5:21:10, 12,345.68
InvariantCulture: 05/12/2021 05:21:10, 12,345.68
CurrentCulture  : 2021/05/12 5:21:10, 12,345.68
InvariantCulture: 05/12/2021 05:21:10, 12,345.68
fr-FR-Culture   : 12/05/2021 05:21:10, 12 345,68
*/

InvariantCulture での文字列補完が必要なケース

日付の表記や、数値の桁区切りと小数点記号、通貨記号などは国や文化によって異なります。
C#では、OS実行環境等から現在の国と文化を得て、CultureInfo.CurrentCulture に情報を保持しています。
そして C#の文字列補完 $"{}" は、CultureInfo.CurrentCulture に従って日付や数値を文字列化します。

UI上に表示する文字列は CultureInfo.CurrentCulture に従った内容で良いのですが、クラウドやファイル上にデータを文字列化して保存する場合は、文字列化に用いた CultureInfo.CurrentCulture の内容を同時に記録しないと、データの解釈ができなくなります。それでは困るので特定の国や文化に依存しない中立的な表記で記録したいのですが、それに用いるのが CultureInfo.InvariantCulture です。

CultureInfo.InvariantCulture はC/C++言語における"C"ロカールに相当し、基本的に米国文化の内容です。

CultureInfo を指定して文字列補完するには

日付変数や実数変数の個々の文字列化であれば、ToString (string? format, IFormatProvider? provider)ToString (IFormatProvider? provider) を用い、引数に CultureInfo を渡すことで、指定の CultureInfo に従った文字列化ができます。

文字列補完の場合は、FormattableString.ToString (IFormatProvider? formatProvider) を用い、FormattableString fmt = $"{val}"; fmt.ToString(cultureInfo); のように指定できますが、FormattableString を宣言する手間が必要となります。CultureInfo.InvariantCulture に限って、その手間を省くのが FormattableString.Invariant(FormattableString) Method なのです。

逆に同じ文字列補完に対して、複数のCultureInfoを適用したい場合には FormattableString.ToString (IFormatProvider? formatProvider) が有用です。国や文化の違いを並べて表示したり、国や文化をユーザ選択させるようなケースに役立つでしょう。

参考資料

5
3
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
5
3