0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

IFormattableを実装する

Posted at

参考

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

IFormattableインターフェイスのヘルプも、参考にしてください。

動機

ユーザー定義型を文字列表現に変換する際、DateTime型のように、書式指定子を含んだフォーマットを指定したい。

このためには、ユーザー定義型でIFormattableインターフェイスを実装する。

IFormattableインターフェイス

IFormattableを実装するユーザー定義型では、以下のメソッドを実装する必要がある。

string ToString(string? format, IFormatProvider? formatProvider);
  • formatに応じて、オブジェクトの値を文字列表現に変換するよう、メソッドを記述する(動画では、2つの例を実装しています。参考にしてください)
  • formatにどのような書式指定子を含めることができるかは、自由に決めてよい
  • 数値の小数点など、カルチャーに依存した文字列表現へ変換する際には、formatProviderを利用する

利用

  • ToStringメソッドを呼ぶ
Console.WriteLine(obj.ToString("XXX", CultureInfo.CurrentCulture));
  • 複合書式指定を利用する
Console.WriteLine(string.Format("{0:XXX}", obj));

注意

  • 書式指定子としてG(General)は、必ず実装すること
  • formatnullが渡された場合にも、対応すること
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?