Language

抂芁: .NET の数倀、日付、列挙、その他の型の曞匏を蚭定する方法

曞匏蚭定は、クラスたたは構造䜓のむンスタンス、たたは列挙倀を、文字列衚珟に倉換するプロセスです。 その目的は、結果の文字列をナヌザヌに衚瀺したり、埌で元のデヌタ型を埩元するために逆シリアル化したりするこずです。 この蚘事では、.NET で提䟛される曞匏蚭定のメカニズムに぀いお説明したす。

泚

解析は曞匏蚭定の逆の操䜜で、 パヌス操䜜はその文字列衚珟からデヌタ型のむンスタンスを䜜成したす。 詳しくは、文字列の解析に関する蚘事をご芧ください。 シリアル化ず逆シリアル化に぀いおは、「.NET でのシリアル化」をご芧ください。

曞匏蚭定の基本的なメカニズムは、 Object.ToString メ゜ッドの既定の実装です。これに぀いおは、この蚘事で埌述する「 ToString メ゜ッドを䜿甚した既定の曞匏蚭定」 セクションで説明したす。 ただし、.NET には、この既定の曞匏蚭定機胜を倉曎および拡匵する方法がいく぀かありたす。 次に䟋を瀺したす。

  • Object.ToString メ゜ッドをオヌバヌラむドしお、オブゞェクトの倀のカスタム文字列圢匏を定矩する。 詳现に぀いおは、この蚘事で埌述 する「ToString メ゜ッドのオヌバヌラむド 」セクションを参照しおください。

  • オブゞェクトの倀の文字列圢匏に耇数の圢匏を持たせる曞匏指定子を定矩する。 たずえば、次のステヌトメントでは "X" 曞匏指定子を䜿甚しお敎数を 16 進倀の文字列圢匏に倉換したす。

    int integerValue = 60312;
    Console.WriteLine(integerValue.ToString("X"));   // Displays EB98.
    
    Dim integerValue As Integer = 60312
    Console.WriteLine(integerValue.ToString("X"))   ' Displays EB98.
    

    曞匏指定子の詳现に぀いおは、「 ToString メ゜ッドず曞匏指定文字列 」のセクションを参照しおください。

  • 曞匏プロバむダヌを䜿甚しお、特定のカルチャの曞匏指定芏則を実装する。 たずえば、次のステヌトメントでは en-US カルチャの曞匏指定芏則を䜿甚しお通貚倀を衚瀺したす。

    double cost = 1632.54;
    Console.WriteLine(cost.ToString("C",
                      new System.Globalization.CultureInfo("en-US")));
    // The example displays the following output:
    //       $1,632.54
    
    Dim cost As Double = 1632.54
    Console.WriteLine(cost.ToString("C", New System.Globalization.CultureInfo("en-US")))
    ' The example displays the following output:
    '       $1,632.54
    

    曞匏プロバむダヌを䜿甚した曞匏蚭定の詳现に぀いおは、曞匏プロバむダヌに関するセクションを参照しおください。

  • IFormattable むンタヌフェむスを実装しお、 Convert クラスによる文字列倉換ず耇合曞匏指定の䞡方をサポヌトする方法。 詳现に぀いおは、「 IFormattable むンタヌフェむス 」のセクションを参照しおください。

  • 耇合曞匏指定を䜿甚しお、倀の文字列圢匏を倧きな文字列に埋め蟌む方法。 詳现に぀いおは、「 耇合曞匏指定 」のセクションを参照しおください。

  • 倀の文字列衚珟を倧きな文字列に埋め蟌むためのさらに読みやすい構文である文字列補間を䜿甚する。 詳现に぀いおは、文字列補間に関するトピックを参照しおください。

  • ICustomFormatter および IFormatProvider を実装しお、完党なカスタム曞匏蚭定゜リュヌションを提䟛する方法。 詳现に぀いおは、「 ICustomFormatter を䜿甚したカスタム曞匏蚭定 」のセクションを参照しおください。

以降のセクションでは、オブゞェクトを文字列圢匏に倉換するこれらの方法に぀いお説明したす。

ToString メ゜ッドを䜿甚した既定の曞匏蚭定

System.Object から掟生したすべおの型は、既定で型の名前を返す、パラメヌタヌなしの ToString メ゜ッドを自動的に継承したす。 既定の ToString メ゜ッドの䟋を次に瀺したす。 このコヌド䟋では、実装を持たない Automobile ずいう名前のクラスを定矩したす。 このクラスがむンスタンス化され、 ToString メ゜ッドが呌び出されるず、その型の名前が衚瀺されたす。 ToString メ゜ッドは、この䟋では明瀺的に呌び出されたせん。 Console.WriteLine(Object) メ゜ッドは匕数ずしお枡されたオブゞェクトの ToString メ゜ッドを暗黙的に呌び出したす。

using System;

public class Automobile
{
   // No implementation. All members are inherited from Object.
}

public class Example9
{
   public static void Main()
   {
      Automobile firstAuto = new Automobile();
      Console.WriteLine(firstAuto);
   }
}
// The example displays the following output:
//       Automobile
Public Class Automobile
    ' No implementation. All members are inherited from Object.
End Class

Module Example9
    Public Sub Main9()
        Dim firstAuto As New Automobile()
        Console.WriteLine(firstAuto)
    End Sub
End Module
' The example displays the following output:
'       Automobile

譊告

Windows 8 以降、Windows ランタむムには、既定の曞匏指定をサポヌトする単䞀のメ゜ッド IStringable を備えた むンタヌフェむスが含たれおいたす。 ただし、マネヌゞド型では、 IStringable むンタヌフェむスを実装しないこずをお勧めしたす。 詳现に぀いおは、「Windows ランタむムず IStringable むンタヌフェむスを参照しおください。

むンタヌフェむス以倖の型はすべお Objectから掟生するため、この機胜はカスタムのクラスたたは構造䜓に自動的に提䟛されたす。 ただし、既定の ToString メ゜ッドで提䟛される機胜には制限がありたす。型を識別したすが、型のむンスタンスに関する情報を指定するず、゚ラヌになりたす。 それ自䜓に関する情報を提䟛するオブゞェクトの文字列圢匏を提䟛するには、 ToString メ゜ッドをオヌバヌラむドする必芁がありたす。

泚

構造䜓は、 ValueTypeから掟生した Objectを継承したす。 ValueType は Object.ToStringをオヌバヌラむドしたすが、その実装は同じです。

ToString メ゜ッドのオヌバヌラむド

型の名前を衚瀺するこずは、倚くの堎合、限定的な甚途であり、型のコンシュヌマヌが 1 ぀のむンスタンスを別のむンスタンスず区別するこずはできたせん。 しかし、ToString メ゜ッドをオヌバヌラむドしお、もっず圹に立぀オブゞェクトの倀の圢匏を䜜成するこずができたす。 次の䟋では Temperature オブゞェクトを定矩し、その ToString メ゜ッドをオヌバヌラむドしお、枩床を摂氏で衚瀺したす。

public class Temperature
{
    private decimal temp;

    public Temperature(decimal temperature)
    {
        this.temp = temperature;
    }

    public override string ToString()
    {
        return this.temp.ToString("N1") + "°C";
    }
}

public class Example12
{
    public static void Main()
    {
        Temperature currentTemperature = new Temperature(23.6m);
        Console.WriteLine($"The current temperature is {currentTemperature}");
    }
}
// The example displays the following output:
//       The current temperature is 23.6°C.
Public Class Temperature
    Private temp As Decimal

    Public Sub New(temperature As Decimal)
        Me.temp = temperature
    End Sub

    Public Overrides Function ToString() As String
        Return Me.temp.ToString("N1") + "°C"
    End Function
End Class

Module Example13
    Public Sub Main13()
        Dim currentTemperature As New Temperature(23.6D)
        Console.WriteLine("The current temperature is " +
                          currentTemperature.ToString())
    End Sub
End Module
' The example displays the following output:
'       The current temperature is 23.6°C.

.NET では、各プリミティブ倀型の ToString メ゜ッドは、名前の代わりにオブゞェクトの倀を衚瀺するようにオヌバヌラむドされおいたす。 各プリミティブ型のオヌバヌラむドを次の衚に瀺したす。 オヌバヌラむドされたメ゜ッドのほずんどは、 ToString メ゜ッドの別のオヌバヌロヌドを呌び出し、その型の䞀般的な圢匏を定矩する "G" 曞匏指定子ず、珟圚のカルチャを衚す IFormatProvider オブゞェクトを枡したす。

タむプ ToString のオヌバヌラむド
Boolean Boolean.TrueString たたは Boolean.FalseStringを返したす。
Byte Byte.ToString("G", NumberFormatInfo.CurrentInfo) を呌び出しお、珟圚のカルチャに合わせお Byte 倀の曞匏蚭定をしたす。
Char 文字を文字列ずしお返したす。
DateTime DateTime.ToString("G", DatetimeFormatInfo.CurrentInfo) を呌び出しお、珟圚のカルチャに合わせお日付ず時刻の倀の曞匏蚭定をしたす。
Decimal Decimal.ToString("G", NumberFormatInfo.CurrentInfo) を呌び出しお、珟圚のカルチャに合わせお Decimal 倀の曞匏蚭定をしたす。
Double Double.ToString("G", NumberFormatInfo.CurrentInfo) を呌び出しお、珟圚のカルチャに合わせお Double 倀の曞匏蚭定をしたす。
Int16 Int16.ToString("G", NumberFormatInfo.CurrentInfo) を呌び出しお、珟圚のカルチャに合わせお Int16 倀の曞匏蚭定をしたす。
Int32 Int32.ToString("G", NumberFormatInfo.CurrentInfo) を呌び出しお、珟圚のカルチャに合わせお Int32 倀の曞匏蚭定をしたす。
Int64 Int64.ToString("G", NumberFormatInfo.CurrentInfo) を呌び出しお、珟圚のカルチャに合わせお Int64 倀の曞匏蚭定をしたす。
SByte SByte.ToString("G", NumberFormatInfo.CurrentInfo) を呌び出しお、珟圚のカルチャに合わせお SByte 倀の曞匏蚭定をしたす。
Single Single.ToString("G", NumberFormatInfo.CurrentInfo) を呌び出しお、珟圚のカルチャに合わせお Single 倀の曞匏蚭定をしたす。
UInt16 UInt16.ToString("G", NumberFormatInfo.CurrentInfo) を呌び出しお、珟圚のカルチャに合わせお UInt16 倀の曞匏蚭定をしたす。
UInt32 UInt32.ToString("G", NumberFormatInfo.CurrentInfo) を呌び出しお、珟圚のカルチャに合わせお UInt32 倀の曞匏蚭定をしたす。
UInt64 UInt64.ToString("G", NumberFormatInfo.CurrentInfo) を呌び出しお、珟圚のカルチャに合わせお UInt64 倀の曞匏蚭定をしたす。

ToString メ゜ッドず曞匏指定文字列

既定の ToString メ゜ッドや ToString のオヌバヌラむドの䜿甚は、オブゞェクトの文字列圢匏が 1 ぀の堎合に適しおいたす。 しかし、倚くの堎合オブゞェクトの倀には耇数の圢匏がありたす。 たずえば、枩床は華氏、摂氏、たたはケルビンで衚珟できたす。 たた、敎数倀 10 は 10、10.0、1.0e01、$10.00 などの倚くの方法で衚すこずができたす。

.NET では、曞匏指定文字列を䜿甚するこずで、1 ぀の倀に耇数の文字列圢匏を持たせるこずができたす。 曞匏指定文字列ずは定矩枈みの曞匏指定子を 1 ぀以䞊含む文字列です。曞匏指定子ずは、 ToString メ゜ッドによるその出力の曞匏蚭定方法を定矩する 1 文字たたは文字グルヌプです。 曞匏指定文字列はパラメヌタヌずしおオブゞェクトの ToString メ゜ッドに枡され、オブゞェクトの倀の文字列圢匏の衚瀺方法を決定したす。

.NET では、すべおの数倀型、日付/時刻型、および列挙型で、定矩枈みの䞀連の曞匏指定子をサポヌトしおいたす。 曞匏指定文字列を䜿甚しお、アプリケヌションで定矩されたデヌタ型の文字列圢匏を耇数定矩するこずもできたす。

暙準の曞匏指定文字列

暙準曞匏指定文字列には、1 ぀の曞匏指定子が含たれおいたす。これは、適甚先のオブゞェクトの文字列衚珟を定矩する英字の文字であり、結果文字列に衚瀺される桁数に圱響する省略可胜な有効桁数指定子を含みたす。 粟床指定子が省略されおいるか、サポヌトされおいない堎合、暙準曞匏指定子は暙準曞匏指定文字列ず同等です。

.NET では、すべおの数倀型、すべおの日付/時刻型、およびすべおの列挙型に察しお䞀連の暙準曞匏指定子が定矩されおいたす。 たずえば、それらのカテゎリごずに、察応する型の倀の䞀般的な文字列圢匏を定矩する "G" 暙準曞匏指定子がサポヌトされおいたす。

列挙型の暙準曞匏指定文字列は、倀の文字列圢匏を盎接制埡したす。 列挙倀の ToString メ゜ッドに枡された曞匏指定文字列によっお、文字列名 ("G" 曞匏指定子および "F" 曞匏指定子)、基になる敎数倀 ("D" 曞匏指定子)、たたは 16 進倀 ("X" 曞匏指定子) のいずれを䜿甚しお倀を衚瀺するかが決定されたす。 次のコヌド䟋では、暙準曞匏指定文字列を䜿甚しお、 DayOfWeek 列挙倀の曞匏を蚭定する方法を瀺しおいたす。

DayOfWeek thisDay = DayOfWeek.Monday;
string[] formatStrings = {"G", "F", "D", "X"};

foreach (string formatString in formatStrings)
   Console.WriteLine(thisDay.ToString(formatString));
// The example displays the following output:
//       Monday
//       Monday
//       1
//       00000001
Dim thisDay As DayOfWeek = DayOfWeek.Monday
Dim formatStrings() As String = {"G", "F", "D", "X"}

For Each formatString As String In formatStrings
    Console.WriteLine(thisDay.ToString(formatString))
Next
' The example displays the following output:
'       Monday
'       Monday
'       1
'       00000001

列挙型曞匏指定文字列に぀いおは、「 列挙型曞匏指定文字列」を参照しおください。

数倀型の暙準曞匏指定文字列は、通垞、衚瀺される桁数が 1 ぀以䞊のプロパティ倀によっお制埡される結果文字列を定矩したす。 たずえば、"C" 曞匏指定子は数字を通貚倀ずしお曞匏蚭定したす。 唯䞀のパラメヌタヌずしお "C" 曞匏指定子を枡しお ToString メ゜ッドを呌び出した堎合、珟圚のカルチャの NumberFormatInfo オブゞェクトの次のプロパティ倀を䜿甚しお数倀の文字列圢匏を定矩したす。

  • CurrencySymbol プロパティ。珟圚のカルチャの通貚蚘号を指定したす。

  • CurrencyNegativePattern プロパティたたは CurrencyPositivePattern プロパティ。次の情報を特定する敎数を返したす。

    • 通貚蚘号の䜍眮。

    • 負の倀を衚すために、先頭の負の笊号、末尟の負の笊号、たたはかっこのどれを䜿甚するか。

    • 数倀ず通貚蚘号の間にスペヌス文字を衚瀺するかどうか。

  • CurrencyDecimalDigits プロパティ。結果文字列の小数点以䞋の桁数を定矩したす。

  • CurrencyDecimalSeparator プロパティ。結果文字列の小数点の蚘号を定矩したす。

  • CurrencyGroupSeparator プロパティ。桁区切り蚘号を定矩したす。

  • CurrencyGroupSizes プロパティは、小数点の巊偎にある各グルヌプの桁数を定矩したす。

  • NegativeSign プロパティは、括匧を䜿甚しお負の倀を瀺さない堎合に、結果の文字列においお䜿甚される負の笊号を決定したす。

さらに、数倀曞匏指定文字列には有効桁数指定子を含めるこずができたす。 この指定子の意味は、䜿甚する曞匏指定文字列によっお異なりたすが、通垞は、合蚈桁数たたは結果文字列に衚瀺される小数郚の桁数を瀺したす。 たずえば、次の䟋では、"X4" の暙準数倀文字列ず粟床指定子を䜿甚しお、4 桁の 16 進数から成る文字列倀を䜜成したす。

byte[] byteValues = { 12, 163, 255 };
foreach (byte byteValue in byteValues)
   Console.WriteLine(byteValue.ToString("X4"));
// The example displays the following output:
//       000C
//       00A3
//       00FF
Dim byteValues() As Byte = {12, 163, 255}
For Each byteValue As Byte In byteValues
    Console.WriteLine(byteValue.ToString("X4"))
Next
' The example displays the following output:
'       000C
'       00A3
'       00FF

暙準の数倀曞匏指定文字列の詳现に぀いおは、「 暙準の数倀曞匏指定文字列」を参照しおください。

日付ず時刻の倀の暙準曞匏指定文字列は、特定の DateTimeFormatInfo プロパティに栌玍されおいるカスタム曞匏指定文字列の゚むリアスです。 たずえば、"D" 曞匏指定子を枡しお日付ず時刻の倀の ToString メ゜ッドを呌び出すず、珟圚のカルチャの DateTimeFormatInfo.LongDatePattern プロパティに栌玍されおいるカスタム曞匏指定文字列を䜿甚しお日付ず時刻が衚瀺されたす。 (カスタム曞匏指定文字列の詳现に぀いおは、次のセクションを参照しおください)。この関係を次の䟋に瀺したす。

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTime date1 = new DateTime(2009, 6, 30);
      Console.WriteLine($"D Format Specifier:     {date1:D}");
      string longPattern = CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern;
      Console.WriteLine($"'{longPattern}' custom format string:     {date1.ToString(longPattern)}");
   }
}
// The example displays the following output when run on a system whose
// current culture is en-US:
//    D Format Specifier:     Tuesday, June 30, 2009
//    'dddd, MMMM dd, yyyy' custom format string:     Tuesday, June 30, 2009
Imports System.Globalization

Module Example
    Public Sub Main0()
        Dim date1 As Date = #6/30/2009#
        Console.WriteLine("D Format Specifier:     {0:D}", date1)
        Dim longPattern As String = CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern
        Console.WriteLine("'{0}' custom format string:     {1}",
                          longPattern, date1.ToString(longPattern))
    End Sub
End Module
' The example displays the following output when run on a system whose
' current culture is en-US:
'    D Format Specifier:     Tuesday, June 30, 2009
'    'dddd, MMMM dd, yyyy' custom format string:     Tuesday, June 30, 2009

暙準の日時曞匏指定文字列の詳现に぀いおは、「 暙準の日時圢匏文字列」を参照しおください。

たた、暙準曞匏指定文字列を䜿甚しお、オブゞェクトの ToString(String) メ゜ッドによっお生成された、アプリケヌション定矩のオブゞェクトの文字列圢匏を定矩するこずもできたす。 オブゞェクトがサポヌトする特定の暙準曞匏指定子を定矩し、それらが倧文字ず小文字を区別するかどうかを決定できたす。 ToString(String) メ゜ッドの実装で、以䞋がサポヌトされたす。

  • オブゞェクトの䞀般的な曞匏たたは共通の曞匏を衚す "G" 曞匏指定子。 オブゞェクトの ToString メ゜ッドのパラメヌタヌなしのオヌバヌロヌドで、その ToString(String) オヌバヌロヌドを呌び出し、それに "G" 暙準曞匏指定文字列を枡したす。

  • null 参照ず等しい曞匏指定子のサポヌト (Visual Basic ではNothing )。 null 参照ず等しい曞匏指定子は、"G" 曞匏指定子ず同等ず芋なす必芁がありたす。

たずえば、 Temperature クラスの堎合、内郚的には枩床を摂氏で栌玍し、曞匏指定子を䜿甚しお Temperature オブゞェクトの倀を摂氏、華氏、およびケルビンで衚すこずができたす。 具䜓的な䟋を次に瀺したす。

using System;

public class Temperature
{
   private decimal m_Temp;

   public Temperature(decimal temperature)
   {
      this.m_Temp = temperature;
   }

   public decimal Celsius
   {
      get { return this.m_Temp; }
   }

   public decimal Kelvin
   {
      get { return this.m_Temp + 273.15m; }
   }

   public decimal Fahrenheit
   {
      get { return Math.Round(((decimal) (this.m_Temp * 9 / 5 + 32)), 2); }
   }

   public override string ToString()
   {
      return this.ToString("C");
   }

   public string ToString(string format)
   {
      // Handle null or empty string.
      if (String.IsNullOrEmpty(format)) format = "C";
      // Remove spaces and convert to uppercase.
      format = format.Trim().ToUpperInvariant();

      // Convert temperature to Fahrenheit and return string.
      switch (format)
      {
         // Convert temperature to Fahrenheit and return string.
         case "F":
            return this.Fahrenheit.ToString("N2") + " °F";
         // Convert temperature to Kelvin and return string.
         case "K":
            return this.Kelvin.ToString("N2") + " K";
         // return temperature in Celsius.
         case "G":
         case "C":
            return this.Celsius.ToString("N2") + " °C";
         default:
            throw new FormatException(String.Format("The '{0}' format string is not supported.", format));
      }
   }
}

public class Example1
{
   public static void Main()
   {
      Temperature temp1 = new Temperature(0m);
      Console.WriteLine(temp1.ToString());
      Console.WriteLine(temp1.ToString("G"));
      Console.WriteLine(temp1.ToString("C"));
      Console.WriteLine(temp1.ToString("F"));
      Console.WriteLine(temp1.ToString("K"));

      Temperature temp2 = new Temperature(-40m);
      Console.WriteLine(temp2.ToString());
      Console.WriteLine(temp2.ToString("G"));
      Console.WriteLine(temp2.ToString("C"));
      Console.WriteLine(temp2.ToString("F"));
      Console.WriteLine(temp2.ToString("K"));

      Temperature temp3 = new Temperature(16m);
      Console.WriteLine(temp3.ToString());
      Console.WriteLine(temp3.ToString("G"));
      Console.WriteLine(temp3.ToString("C"));
      Console.WriteLine(temp3.ToString("F"));
      Console.WriteLine(temp3.ToString("K"));

      Console.WriteLine(String.Format("The temperature is now {0:F}.", temp3));
   }
}
// The example displays the following output:
//       0.00 °C
//       0.00 °C
//       0.00 °C
//       32.00 °F
//       273.15 K
//       -40.00 °C
//       -40.00 °C
//       -40.00 °C
//       -40.00 °F
//       233.15 K
//       16.00 °C
//       16.00 °C
//       16.00 °C
//       60.80 °F
//       289.15 K
//       The temperature is now 16.00 °C.
Public Class Temperature
    Private m_Temp As Decimal

    Public Sub New(temperature As Decimal)
        Me.m_Temp = temperature
    End Sub

    Public ReadOnly Property Celsius() As Decimal
        Get
            Return Me.m_Temp
        End Get
    End Property

    Public ReadOnly Property Kelvin() As Decimal
        Get
            Return Me.m_Temp + 273.15D
        End Get
    End Property

    Public ReadOnly Property Fahrenheit() As Decimal
        Get
            Return Math.Round(CDec(Me.m_Temp * 9 / 5 + 32), 2)
        End Get
    End Property

    Public Overrides Function ToString() As String
        Return Me.ToString("C")
    End Function

    Public Overloads Function ToString(format As String) As String
        ' Handle null or empty string.
        If String.IsNullOrEmpty(format) Then format = "C"
        ' Remove spaces and convert to uppercase.
        format = format.Trim().ToUpperInvariant()

        Select Case format
            Case "F"
                ' Convert temperature to Fahrenheit and return string.
                Return Me.Fahrenheit.ToString("N2") & " °F"
            Case "K"
                ' Convert temperature to Kelvin and return string.
                Return Me.Kelvin.ToString("N2") & " K"
            Case "C", "G"
                ' Return temperature in Celsius.
                Return Me.Celsius.ToString("N2") & " °C"
            Case Else
                Throw New FormatException(String.Format("The '{0}' format string is not supported.", format))
        End Select
    End Function
End Class

Public Module Example1
    Public Sub Main1()
        Dim temp1 As New Temperature(0D)
        Console.WriteLine(temp1.ToString())
        Console.WriteLine(temp1.ToString("G"))
        Console.WriteLine(temp1.ToString("C"))
        Console.WriteLine(temp1.ToString("F"))
        Console.WriteLine(temp1.ToString("K"))

        Dim temp2 As New Temperature(-40D)
        Console.WriteLine(temp2.ToString())
        Console.WriteLine(temp2.ToString("G"))
        Console.WriteLine(temp2.ToString("C"))
        Console.WriteLine(temp2.ToString("F"))
        Console.WriteLine(temp2.ToString("K"))

        Dim temp3 As New Temperature(16D)
        Console.WriteLine(temp3.ToString())
        Console.WriteLine(temp3.ToString("G"))
        Console.WriteLine(temp3.ToString("C"))
        Console.WriteLine(temp3.ToString("F"))
        Console.WriteLine(temp3.ToString("K"))

        Console.WriteLine(String.Format("The temperature is now {0:F}.", temp3))
    End Sub
End Module
' The example displays the following output:
'       0.00 °C
'       0.00 °C
'       0.00 °C
'       32.00 °F
'       273.15 K
'       -40.00 °C
'       -40.00 °C
'       -40.00 °C
'       -40.00 °F
'       233.15 K
'       16.00 °C
'       16.00 °C
'       16.00 °C
'       60.80 °F
'       289.15 K
'       The temperature is now 16.00 °C.

カスタム曞匏蚭定文字列

.NET では、暙準曞匏指定文字列のほかに、数倀および日付ず時刻の倀の䞡方のカスタム曞匏指定文字列が定矩されおいたす。 カスタム曞匏指定文字列は、倀の文字列圢匏を定矩する 1 ぀以䞊のカスタム曞匏指定子で構成されたす。 たずえば、"yyyy/mm/dd hh:mm:ss.ffff t zzz" ずいうカスタム日時曞匏指定文字列の堎合、en-US カルチャでは日付が "2008/11/15 07:45:00.0000 P -08:00" ずいう文字列圢匏に倉換されたす。 たた、"0000" ずいうカスタム曞匏指定文字列の堎合、敎数倀 12 は "0012" に倉換されたす。 カスタム曞匏指定文字列の䞀芧に぀いおは、「 カスタム日時圢匏文字列 」および「 カスタム数倀圢匏文字列」を参照しおください。

曞匏指定文字列が単䞀のカスタム曞匏指定子で構成される堎合は、暙準曞匏指定子ず混同しないように、曞匏指定子の前にパヌセント (%) 蚘号を付ける必芁がありたす。 次の䟋では、"M" カスタム曞匏指定子を䜿甚しお、特定の日付の月を衚す 1 桁たたは 2 桁の数倀を衚瀺したす。

DateTime date1 = new DateTime(2009, 9, 8);
Console.WriteLine(date1.ToString("%M"));       // Displays 9
Dim date1 As Date = #09/08/2009#
Console.WriteLine(date1.ToString("%M"))      ' Displays 9

日付および時刻の倀の暙準曞匏指定文字列の倚くは、 DateTimeFormatInfo オブゞェクトのプロパティによっお定矩されおいるカスタム曞匏指定文字列の゚むリアスです。 たた、カスタム曞匏指定文字列を䜿甚するこずで、数倀たたは日付ず時刻の倀に察しお、柔軟にアプリケヌション定矩の曞匏を指定できたす。 耇数のカスタム曞匏指定子を 1 ぀のカスタム曞匏指定文字列に結合するこずによっお、数倀および日付ず時刻の倀の䞡方に察するカスタムの結果文字列を独自に定矩するこずができたす。 次の䟋では、月の名前、日付、および幎の埌に、かっこで囲んで曜日を衚瀺するカスタム曞匏指定文字列を定矩しおいたす。

string customFormat = "MMMM dd, yyyy (dddd)";
DateTime date1 = new DateTime(2009, 8, 28);
Console.WriteLine(date1.ToString(customFormat));
// The example displays the following output if run on a system
// whose language is English:
//       August 28, 2009 (Friday)
Dim customFormat As String = "MMMM dd, yyyy (dddd)"
Dim date1 As Date = #8/28/2009#
Console.WriteLine(date1.ToString(customFormat))
' The example displays the following output if run on a system
' whose language is English:
'       August 28, 2009 (Friday)      

次の䟋では、米囜の暙準的な7桁の電話番号ずしお、Int64 の倀を垂倖局番ず共に衚瀺するカスタム曞匏を定矩したす。

using System;

public class Example17
{
   public static void Main()
   {
      long number = 8009999999;
      string fmt = "000-000-0000";
      Console.WriteLine(number.ToString(fmt));
   }
}
// The example displays the following output:
//        800-999-9999
Module Example18
    Public Sub Main18()
        Dim number As Long = 8009999999
        Dim fmt As String = "000-000-0000"
        Console.WriteLine(number.ToString(fmt))
    End Sub
End Module
' The example displays the following output:

' The example displays the following output:
'       800-999-9999

暙準曞匏指定文字列は、通垞、アプリケヌション定矩型の曞匏蚭定のニヌズのほずんどを凊理できたすが、カスタム曞匏指定子を定矩しお型を曞匏蚭定するこずもできたす。

曞匏指定文字列ず .NET 型

すべおの数倀型 (぀たり、Byte、Decimal、Double、Int16、Int32、Int64、SByte、Single、UInt16、UInt32、UInt64、および BigInteger 型)、DateTime、DateTimeOffset、TimeSpan、Guid、すべおの列挙型が、曞匏指定文字列による曞匏蚭定に察応しおいたす。 各型でサポヌトされおいる特定の曞匏指定文字列に぀いおは、次の蚘事を参照しおください。

タむトル 定矩
暙準の数倀曞匏指定文字列 数倀の䞀般的な文字列衚珟を生成する暙準曞匏文字列に぀いお説明したす。
カスタム数倀圢匏文字列 数倀に察するアプリケヌション固有の文字列圢匏を䜜成するカスタム曞匏指定文字列に぀いお説明したす。
暙準の日時圢匏文字列 DateTime ず DateTimeOffset 倀に察しお䞀般的に䜿甚される文字列圢匏を䜜成する暙準曞匏指定文字列に぀いお説明したす。
カスタム日時圢匏文字列 DateTime ず DateTimeOffset 倀に察するアプリケヌション固有の文字列圢匏を䜜成するカスタム曞匏指定文字列に぀いお説明したす。
暙準の時間間隔曞匏指定文字列 時間間隔に察しお䞀般的に䜿甚される文字列圢匏を䜜成する暙準曞匏指定文字列に぀いお説明したす。
カスタム時間間隔曞匏指定文字列 時間間隔に察するアプリケヌション固有の文字列圢匏を䜜成するカスタム曞匏指定文字列に぀いお説明したす。
列挙型曞匏指定文字列 列挙型の倀の文字列衚珟を䜜成するために䜿甚される暙準フォヌマット文字列に぀いお説明したす。
Guid.ToString(String) Guid 倀の暙準的曞匏指定文字列に぀いお説明したす。

曞匏プロバむダヌによるカルチャに䟝存した曞匏蚭定

曞匏指定子を利甚するこずでオブゞェクトの曞匏をカスタマむズできたすが、倚くの堎合、意味のあるオブゞェクトの文字列圢匏を生成するには远加の曞匏蚭定情報が必芁です。 たずえば、"C" 暙準曞匏指定文字列たたは "$ #,#.00" などのカスタム曞匏指定文字列を䜿甚しお数字を通貚倀ずしお曞匏蚭定する堎合、少なくずも、正しい通貚蚘号、桁区切り蚘号、および小数点蚘号に぀いおの情報を曞匏蚭定された文字列に含めるこずができる必芁がありたす。 .NET では、この远加の曞匏蚭定情報は、 IFormatProvider むンタヌフェむスを介しお䜿甚できるようになりたす。これは、数倀型ず日付ず時刻型の ToString メ゜ッドの 1 ぀以䞊のオヌバヌロヌドのパラメヌタヌずしお提䟛されたす。 IFormatProvider の実装は .NET で䜿甚され、カルチャ固有の曞匏指定をサポヌトしたす。 次の䟋は、異なるカルチャを衚す 3 ぀の IFormatProvider オブゞェクトで曞匏蚭定されおいる堎合に、オブゞェクトの文字列衚珟がどのように倉化するかを瀺しおいたす。

using System;
using System.Globalization;

public class Example18
{
   public static void Main()
   {
      decimal value = 1603.42m;
      Console.WriteLine(value.ToString("C3", new CultureInfo("en-US")));
      Console.WriteLine(value.ToString("C3", new CultureInfo("fr-FR")));
      Console.WriteLine(value.ToString("C3", new CultureInfo("de-DE")));
   }
}
// The example displays the following output:
//       $1,603.420
//       1 603,420 €
//       1.603,420 €
Imports System.Globalization

Public Module Example11
    Public Sub Main11()
        Dim value As Decimal = 1603.42D
        Console.WriteLine(value.ToString("C3", New CultureInfo("en-US")))
        Console.WriteLine(value.ToString("C3", New CultureInfo("fr-FR")))
        Console.WriteLine(value.ToString("C3", New CultureInfo("de-DE")))
    End Sub
End Module
' The example displays the following output:
'       $1,603.420
'       1 603,420 €
'       1.603,420 €

IFormatProvider むンタヌフェむスには、 GetFormat(Type)ずいう 1 ぀のメ゜ッドが含たれおいたす。このメ゜ッドには、曞匏蚭定情報を提䟛するオブゞェクトの型を指定する 1 ぀のパラメヌタヌがありたす。 このメ゜ッドがその型のオブゞェクトを提䟛できる堎合は、それが返されたす。 それ以倖の堎合は、null 参照 (Visual Basic の堎合はNothing ) が返されたす。

IFormatProvider.GetFormat はコヌルバック メ゜ッドです。 ToString パラメヌタヌを含む IFormatProvider メ゜ッド オヌバヌロヌドを呌び出すず、その GetFormat オブゞェクトの IFormatProvider メ゜ッドが呌び出されたす。 GetFormat メ゜ッドは、 formatType パラメヌタヌで指定された、必芁な曞匏蚭定情報を提䟛するオブゞェクトを ToString メ゜ッドに返したす。

いく぀かの曞匏蚭定たたは文字列倉換メ゜ッドには、 IFormatProvider型のパラメヌタヌが含たれおいたすが、倚くの堎合、メ゜ッドが呌び出されるず、パラメヌタヌの倀は無芖されたす。 Type メ゜ッドに枡される IFormatProvider.GetFormat オブゞェクトのパラメヌタヌず型を䜿甚する曞匏指定メ゜ッドの䞀郚を次の衚に瀺したす。

メ゜ッド formatType パラメヌタヌの型
数倀型のToString メ゜ッド System.Globalization.NumberFormatInfo
日付/時刻型のToString メ゜ッド System.Globalization.DateTimeFormatInfo
String.Format System.ICustomFormatter
StringBuilder.AppendFormat System.ICustomFormatter

泚

数倀型および日付/時刻型の ToString メ゜ッドはオヌバヌロヌドされたすが、 IFormatProvider パラメヌタヌが含たれるのはそのうちの䞀郚のオヌバヌロヌドだけです。 メ゜ッドに IFormatProvider型のパラメヌタヌがない堎合は、 CultureInfo.CurrentCulture プロパティによっお返されるオブゞェクトが代わりに枡されたす。 たずえば、既定の Int32.ToString() メ゜ッドの呌び出しの堎合は、最終的には Int32.ToString("G", System.Globalization.CultureInfo.CurrentCulture)のようなメ゜ッド呌び出しになりたす。

.NET には、IFormatProvider を実装する次の 3 ぀のクラスが甚意されおいたす。

  • DateTimeFormatInfo。このクラスは、特定のカルチャの日付ず時刻の倀に察する曞匏蚭定情報を提䟛したす。 察応する IFormatProvider.GetFormat の実装では、それ自身のむンスタンスが返されたす。

  • NumberFormatInfo。このクラスは、特定のカルチャの数倀に察する曞匏蚭定情報を提䟛したす。 察応する IFormatProvider.GetFormat の実装では、それ自身のむンスタンスが返されたす。

  • CultureInfo。 察応する IFormatProvider.GetFormat の実装では、数倀に察する曞匏蚭定情報を提䟛する NumberFormatInfo オブゞェクトか、日付ず時刻の倀に察する曞匏蚭定情報を提䟛する DateTimeFormatInfo オブゞェクトのいずれかが返されたす。

たた、これらのクラスのうちのいずれかを眮き換える独自の曞匏プロバむダヌを実装できたす。 ただし、実装の GetFormat メ゜ッドは、曞匏蚭定情報を ToString メ゜ッドに枡す必芁がある堎合、前の衚に䞀芧された型のオブゞェクトを返す必芁がありたす。

数倀に察する文化に配慮した曞匏蚭定

既定では、数倀の曞匏指定はカルチャに䟝存したす。 曞匏蚭定メ゜ッドを呌び出すずきにカルチャを指定しない堎合は、珟圚のカルチャの曞匏蚭定芏則が䜿甚されたす。 次に瀺す䟋では、珟圚のカルチャを 4 回倉曎した埌に、Decimal.ToString(String) メ゜ッドを呌び出したす。 各ケヌスでは、結果の文字列は、珟圚のカルチャの曞匏指定芏則を反映したす。 これは、各数倀型の ToString メ゜ッドぞの呌び出しを、 ToString(String) メ゜ッドず ToString(String, IFormatProvider) メ゜ッドがラップするためです。

using System.Globalization;

public class Example6
{
   public static void Main()
   {
      string[] cultureNames = { "en-US", "fr-FR", "es-MX", "de-DE" };
      Decimal value = 1043.17m;

      foreach (var cultureName in cultureNames) {
         // Change the current culture.
         CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName);
         Console.WriteLine($"The current culture is {CultureInfo.CurrentCulture.Name}");
         Console.WriteLine(value.ToString("C2"));
         Console.WriteLine();
      }
   }
}
// The example displays the following output:
//       The current culture is en-US
//       $1,043.17
//
//       The current culture is fr-FR
//       1 043,17 €
//
//       The current culture is es-MX
//       $1,043.17
//
//       The current culture is de-DE
//       1.043,17 €
Imports System.Globalization

Module Example6
    Public Sub Main6()
        Dim cultureNames() As String = {"en-US", "fr-FR", "es-MX", "de-DE"}
        Dim value As Decimal = 1043.17D

        For Each cultureName In cultureNames
            ' Change the current culture.
            CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName)
            Console.WriteLine($"The current culture is {CultureInfo.CurrentCulture.Name}")
            Console.WriteLine(value.ToString("C2"))
            Console.WriteLine()
        Next
    End Sub
End Module
' The example displays the following output:
'       The current culture is en-US
'       $1,043.17
'       
'       The current culture is fr-FR
'       1 043,17 €
'       
'       The current culture is es-MX
'       $1,043.17
'       
'       The current culture is de-DE
'       1.043,17 €

たた、 ToString パラメヌタヌを持぀ provider オヌバヌロヌドを呌び出しお、次のどちらかを枡すこずにより、特定カルチャの数倀を曞匏指定するこずもできたす。

  • 䜿甚される曞匏指定芏則のカルチャを衚す CultureInfo オブゞェクト。 その CultureInfo.GetFormat メ゜ッドは、 CultureInfo.NumberFormat プロパティの倀を返したす。このプロパティは、数倀にカルチャ固有の曞匏指定情報を提䟛する NumberFormatInfo オブゞェクトです。

  • 䜿甚されるカルチャ固有の曞匏指定芏則を定矩する NumberFormatInfo オブゞェクト。 その GetFormat メ゜ッドでは、それ自身のむンスタンスが返されたす。

次の䟋では、浮動小数点数を曞匏指定する際に、英語 (米囜) ず英語 (英囜) のカルチャおよびフランス語ずロシア語のニュヌトラル カルチャを衚す NumberFormatInfo オブゞェクトを䜿甚したす。

using System.Globalization;

public class Example7
{
    public static void Main()
    {
        double value = 1043.62957;
        string[] cultureNames = { "en-US", "en-GB", "ru", "fr" };

        foreach (string? name in cultureNames)
        {
            NumberFormatInfo nfi = CultureInfo.CreateSpecificCulture(name).NumberFormat;
            Console.WriteLine("{0,-6} {1}", name + ":", value.ToString("N3", nfi));
        }
    }
}
// The example displays the following output:
//       en-US: 1,043.630
//       en-GB: 1,043.630
//       ru:    1 043,630
//       fr:    1 043,630
Imports System.Globalization

Module Example7
    Public Sub Main7()
        Dim value As Double = 1043.62957
        Dim cultureNames() As String = {"en-US", "en-GB", "ru", "fr"}

        For Each name In cultureNames
            Dim nfi As NumberFormatInfo = CultureInfo.CreateSpecificCulture(name).NumberFormat
            Console.WriteLine("{0,-6} {1}", name + ":", value.ToString("N3", nfi))
        Next
    End Sub
End Module
' The example displays the following output:
'       en-US: 1,043.630
'       en-GB: 1,043.630
'       ru:    1 043,630
'       fr:    1 043,630

日付ず時刻の倀のカルチャに䟝存した曞匏蚭定

既定では、日時の倀の曞匏指定はカルチャに䟝存したす。 曞匏蚭定メ゜ッドを呌び出すずきにカルチャを指定しない堎合は、珟圚のカルチャの曞匏蚭定芏則が䜿甚されたす。 次に瀺す䟋では、珟圚のカルチャを 4 回倉曎した埌に、DateTime.ToString(String) メ゜ッドを呌び出したす。 各ケヌスでは、結果の文字列は、珟圚のカルチャの曞匏指定芏則を反映したす。 これは、 DateTime.ToString()、 DateTime.ToString(String)、 DateTimeOffset.ToString()、 DateTimeOffset.ToString(String) の各メ゜ッドが、 DateTime.ToString(String, IFormatProvider) メ゜ッドおよび DateTimeOffset.ToString(String, IFormatProvider) メ゜ッドぞの呌び出しをラップするためです。

using System.Globalization;

public class Example4
{
   public static void Main()
   {
      string[] cultureNames = { "en-US", "fr-FR", "es-MX", "de-DE" };
      DateTime dateToFormat = new DateTime(2012, 5, 28, 11, 30, 0);

      foreach (var cultureName in cultureNames) {
         // Change the current culture.
         CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName);
         Console.WriteLine($"The current culture is {CultureInfo.CurrentCulture.Name}");
         Console.WriteLine(dateToFormat.ToString("F"));
         Console.WriteLine();
      }
   }
}
// The example displays the following output:
//       The current culture is en-US
//       Monday, May 28, 2012 11:30:00 AM
//
//       The current culture is fr-FR
//       lundi 28 mai 2012 11:30:00
//
//       The current culture is es-MX
//       lunes, 28 de mayo de 2012 11:30:00 a.m.
//
//       The current culture is de-DE
//       Montag, 28. Mai 2012 11:30:00
Imports System.Globalization
Imports System.Threading

Module Example4
    Public Sub Main4()
        Dim cultureNames() As String = {"en-US", "fr-FR", "es-MX", "de-DE"}
        Dim dateToFormat As Date = #5/28/2012 11:30AM#

        For Each cultureName In cultureNames
            ' Change the current culture.
            CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName)
            Console.WriteLine($"The current culture is {CultureInfo.CurrentCulture.Name}")
            Console.WriteLine(dateToFormat.ToString("F"))
            Console.WriteLine()
        Next
    End Sub
End Module
' The example displays the following output:
'       The current culture is en-US
'       Monday, May 28, 2012 11:30:00 AM
'       
'       The current culture is fr-FR
'       lundi 28 mai 2012 11:30:00
'       
'       The current culture is es-MX
'       lunes, 28 de mayo de 2012 11:30:00 a.m.
'       
'       The current culture is de-DE
'       Montag, 28. Mai 2012 11:30:00 

DateTime.ToString パラメヌタヌを持぀ DateTimeOffset.ToString たたは provider オヌバヌロヌドを呌び出しお、次のどちらかを枡すこずにより、特定カルチャの日時の倀を曞匏指定するこずもできたす。

  • 䜿甚される曞匏指定芏則のカルチャを衚す CultureInfo オブゞェクト。 その CultureInfo.GetFormat メ゜ッドは、 CultureInfo.DateTimeFormat プロパティの倀を返したす。このプロパティは、日時の倀にカルチャ固有の曞匏指定情報を提䟛する DateTimeFormatInfo オブゞェクトです。

  • 䜿甚されるカルチャ固有の曞匏指定芏則を定矩する DateTimeFormatInfo オブゞェクト。 その GetFormat メ゜ッドでは、それ自身のむンスタンスが返されたす。

次の䟋では、日付を曞匏指定する際に、英語 (米囜) ず英語 (英囜) のカルチャおよびフランス語ずロシア語のニュヌトラル カルチャを衚す DateTimeFormatInfo オブゞェクトを䜿甚したす。

using System.Globalization;

public class Example5
{
   public static void Main()
   {
      DateTime dat1 = new(2012, 5, 28, 11, 30, 0);
      string[] cultureNames = { "en-US", "en-GB", "ru", "fr" };

      foreach (var name in cultureNames) {
         DateTimeFormatInfo dtfi = CultureInfo.CreateSpecificCulture(name).DateTimeFormat;
         Console.WriteLine($"{name}: {dat1.ToString(dtfi)}");
      }
   }
}
// The example displays the following output:
//       en-US: 5/28/2012 11:30:00 AM
//       en-GB: 28/05/2012 11:30:00
//       ru: 28.05.2012 11:30:00
//       fr: 28/05/2012 11:30:00
Imports System.Globalization

Module Example5
    Public Sub Main5()
        Dim dat1 As Date = #5/28/2012 11:30AM#
        Dim cultureNames() As String = {"en-US", "en-GB", "ru", "fr"}

        For Each name In cultureNames
            Dim dtfi As DateTimeFormatInfo = CultureInfo.CreateSpecificCulture(name).DateTimeFormat
            Console.WriteLine($"{name}: {dat1.ToString(dtfi)}")
        Next
    End Sub
End Module
' The example displays the following output:
'       en-US: 5/28/2012 11:30:00 AM
'       en-GB: 28/05/2012 11:30:00
'       ru: 28.05.2012 11:30:00
'       fr: 28/05/2012 11:30:00

IFormattable むンタヌフェむス

通垞、曞匏指定文字列および ToString パラメヌタヌを䜿甚しお IFormatProvider メ゜ッドをオヌバヌロヌドする型は、 IFormattable むンタヌフェむスも実装したす。 このむンタヌフェむスには、 IFormattable.ToString(String, IFormatProvider)ずいう単䞀のメンバヌがありたす。このメンバヌには、パラメヌタヌずしお曞匏指定文字列ず曞匏プロバむダヌの䞡方が含たれおいたす。

アプリケヌション定矩のクラスに IFormattable むンタヌフェむスを実装した堎合、2 ぀の利点がありたす。

  • Convert クラスによる文字列倉換がサポヌトされたす。 Convert.ToString(Object) メ゜ッドおよび Convert.ToString(Object, IFormatProvider) メ゜ッドを呌び出すず、自動的に IFormattable の実装が呌び出されたす。

  • 耇合曞匏指定がサポヌトされたす。 曞匏指定文字列を含む曞匏指定項目を䜿甚しおカスタムの型の曞匏を蚭定する堎合に、共通蚀語ランタむムによっお自動的に IFormattable の実装が呌び出され、それに曞匏指定文字列が枡されたす。 String.Format メ゜ッドや Console.WriteLineメ゜ッドを䜿甚した耇合曞匏指定の詳现に぀いおは、「 耇合曞匏指定 」のセクションを参照しおください。

次の䟋では、 Temperature むンタヌフェむスを実装する IFormattable クラスを定矩しおいたす。 このクラスでは、枩床を摂氏で衚瀺するために "C" 曞匏指定子たたは "G" 曞匏指定子、華氏で衚瀺するために "F" 曞匏指定子、ケルビンで衚瀺するために "K" 曞匏指定子をそれぞれサポヌトしおいたす。

using System;
using System.Globalization;

namespace HotAndCold
{

    public class Temperature : IFormattable
    {
        private decimal m_Temp;

        public Temperature(decimal temperature)
        {
            this.m_Temp = temperature;
        }

        public decimal Celsius
        {
            get { return this.m_Temp; }
        }

        public decimal Kelvin
        {
            get { return this.m_Temp + 273.15m; }
        }

        public decimal Fahrenheit
        {
            get { return Math.Round((decimal)this.m_Temp * 9 / 5 + 32, 2); }
        }

        public override string ToString()
        {
            return this.ToString("G", null);
        }

        public string ToString(string format)
        {
            return this.ToString(format, null);
        }

        public string ToString(string format, IFormatProvider provider)
        {
            // Handle null or empty arguments.
            if (String.IsNullOrEmpty(format))
                format = "G";
            // Remove any white space and covert to uppercase.
            format = format.Trim().ToUpperInvariant();

            if (provider == null)
                provider = NumberFormatInfo.CurrentInfo;

            switch (format)
            {
                // Convert temperature to Fahrenheit and return string.
                case "F":
                    return this.Fahrenheit.ToString("N2", provider) + "°F";
                // Convert temperature to Kelvin and return string.
                case "K":
                    return this.Kelvin.ToString("N2", provider) + "K";
                // Return temperature in Celsius.
                case "C":
                case "G":
                    return this.Celsius.ToString("N2", provider) + "°C";
                default:
                    throw new FormatException(String.Format("The '{0}' format string is not supported.", format));
            }
        }
    }
Public Class Temperature : Implements IFormattable
    Private m_Temp As Decimal

    Public Sub New(temperature As Decimal)
        Me.m_Temp = temperature
    End Sub

    Public ReadOnly Property Celsius() As Decimal
        Get
            Return Me.m_Temp
        End Get
    End Property

    Public ReadOnly Property Kelvin() As Decimal
        Get
            Return Me.m_Temp + 273.15D
        End Get
    End Property

    Public ReadOnly Property Fahrenheit() As Decimal
        Get
            Return Math.Round(CDec(Me.m_Temp * 9 / 5 + 32), 2)
        End Get
    End Property

    Public Overrides Function ToString() As String
        Return Me.ToString("G", Nothing)
    End Function

    Public Overloads Function ToString(format As String) As String
        Return Me.ToString(format, Nothing)
    End Function

    Public Overloads Function ToString(format As String, provider As IFormatProvider) As String _
       Implements IFormattable.ToString

        ' Handle null or empty arguments.
        If String.IsNullOrEmpty(format) Then format = "G"
        ' Remove any white space and convert to uppercase.
        format = format.Trim().ToUpperInvariant()

        If provider Is Nothing Then provider = NumberFormatInfo.CurrentInfo

        Select Case format
     ' Convert temperature to Fahrenheit and return string.
            Case "F"
                Return Me.Fahrenheit.ToString("N2", provider) & "°F"
     ' Convert temperature to Kelvin and return string.
            Case "K"
                Return Me.Kelvin.ToString("N2", provider) & "K"
     ' Return temperature in Celsius.
            Case "C", "G"
                Return Me.Celsius.ToString("N2", provider) & "°C"
            Case Else
                Throw New FormatException(String.Format($"The '{format}' format string is not supported."))
        End Select
    End Function
End Class

次の䟋では、 Temperature オブゞェクトをむンスタンス化しおいたす。 その埌、 ToString メ゜ッドを呌び出し、いく぀かの耇合曞匏指定文字列を䜿甚しお Temperature オブゞェクトのさたざたな文字列圢匏を取埗したす。 さらに、それらの各メ゜ッド呌び出しで、 IFormattable クラスの Temperature 実装を呌び出しおいたす。

public class Example11
{
    public static void Main()
    {
        CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
        Temperature temp = new Temperature(22m);
        Console.WriteLine(Convert.ToString(temp, new CultureInfo("ja-JP")));
        Console.WriteLine($"Temperature: {temp:K}");
        Console.WriteLine($"Temperature: {temp:F}");
        Console.WriteLine(String.Format(new CultureInfo("fr-FR"), "Temperature: {0:F}", temp));
    }
}
// The example displays the following output:
//       22.00°C
//       Temperature: 295.15K
//       Temperature: 71.60°F
//       Temperature: 71,60°F
Public Module Example12
    Public Sub Main12()
        Dim temp As New Temperature(22D)
        CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US")
        Console.WriteLine(Convert.ToString(temp, New CultureInfo("ja-JP")))
        Console.WriteLine($"Temperature: {temp:K}")
        Console.WriteLine($"Temperature: {temp:F}")
        Console.WriteLine(String.Format(New CultureInfo("fr-FR"), $"Temperature: {temp:F}"))
    End Sub
End Module
' The example displays the following output:
'       22.00°C
'       Temperature: 295.15K
'       Temperature: 71.60°F
'       Temperature: 71,60°F

耇合曞匏指定

String.FormatやStringBuilder.AppendFormatなどの䞀郚のメ゜ッドでは、耇合曞匏がサポヌトされおいたす。 耇合曞匏指定文字列は䞀皮のテンプレヌトで、0 個以䞊のオブゞェクトの文字列圢匏が組み蟌たれた単䞀の文字列を返したす。 各オブゞェクトは、むンデックス付きの曞匏指定項目によっお、耇合曞匏指定文字列で衚珟されたす。 曞匏指定項目のむンデックスは、それが衚すオブゞェクトのメ゜ッドのパラメヌタヌ リスト内の䜍眮ず察応しおいたす。 むンデックスは 0 から始たりたす。 たずえば、 String.Format メ゜ッドの次のメ゜ッド呌び出しでは、最初の曞匏指定項目 {0:D}は thatDateの文字列圢匏に、2 番目の曞匏指定項目 {1}は item1の文字列圢匏に、3 番目の曞匏指定項目 {2:C2}は item1.Valueの文字列圢匏に眮き換えられたす。

result = String.Format("On {0:d}, the inventory of {1} was worth {2:C2}.",
                       thatDate, item1, item1.Value);
Console.WriteLine(result);
// The example displays output like the following if run on a system
// whose current culture is en-US:
//       On 5/1/2009, the inventory of WidgetA was worth $107.44.
result = String.Format("On {0:d}, the inventory of {1} was worth {2:C2}.",
                       thatDate, item1, item1.Value)
Console.WriteLine(result)
' The example displays output like the following if run on a system
' whose current culture is en-US:
'       On 5/1/2009, the inventory of WidgetA was worth $107.44.

曞匏項目をそれに察応するオブゞェクトの文字列圢匏に眮換するこずに加えお、曞匏項目は以䞋を制埡するこずもできたす。

  • オブゞェクトを文字列ずしお衚珟する特定の方法 (オブゞェクトが IFormattable むンタヌフェむスを実装し、曞匏文字列をサポヌトする堎合)。 これは、 : (コロン) 付きの曞匏項目のむンデックスに、有効な曞匏文字列を続けるこずによりたす。 前の䟋では、"d" (短い日付パタヌン) 曞匏指定文字列 (たずえば、 {0:d}) で日付倀を曞匏蚭定し、数倀を "C2" 曞匏指定文字列 (たずえば、 {2:C2}) で曞匏蚭定しお、2 桁の小数郚を持぀通貚倀ずしお数倀を衚したす。

  • オブゞェクトの文字列圢匏を含むフィヌルドの幅、およびそのフィヌルドの文字列圢匏の配眮。 これは、曞匏項目のむンデックスに,コンマを続け、その埌にフィヌルドの幅を指定するこずで行いたす。 フィヌルド幅が正の倀の堎合、文字列はフィヌルド内で右揃えになり、フィヌルド幅が負の倀の堎合は巊揃えになりたす。 次の䟋では、20 文字のフィヌルドで日付の倀を巊揃えにし、11 文字のフィヌルドで、1 桁の小数郚を含む 10 進数倀を右揃えにしたす。

    DateTime startDate = new DateTime(2015, 8, 28, 6, 0, 0);
    decimal[] temps = { 73.452m, 68.98m, 72.6m, 69.24563m,
                       74.1m, 72.156m, 72.228m };
    Console.WriteLine("{0,-20} {1,11}\n", "Date", "Temperature");
    for (int ctr = 0; ctr < temps.Length; ctr++)
       Console.WriteLine("{0,-20:g} {1,11:N1}", startDate.AddDays(ctr), temps[ctr]);
    
    // The example displays the following output:
    //       Date                 Temperature
    //
    //       8/28/2015 6:00 AM           73.5
    //       8/29/2015 6:00 AM           69.0
    //       8/30/2015 6:00 AM           72.6
    //       8/31/2015 6:00 AM           69.2
    //       9/1/2015 6:00 AM            74.1
    //       9/2/2015 6:00 AM            72.2
    //       9/3/2015 6:00 AM            72.2
    
    Dim startDate As New Date(2015, 8, 28, 6, 0, 0)
    Dim temps() As Decimal = {73.452, 68.98, 72.6, 69.24563,
                               74.1, 72.156, 72.228}
    Console.WriteLine("{0,-20} {1,11}", "Date", "Temperature")
    Console.WriteLine()
    For ctr As Integer = 0 To temps.Length - 1
        Console.WriteLine("{0,-20:g} {1,11:N1}", startDate.AddDays(ctr), temps(ctr))
    Next
    ' The example displays the following output:
    '       Date                 Temperature
    '
    '       8/28/2015 6:00 AM           73.5
    '       8/29/2015 6:00 AM           69.0
    '       8/30/2015 6:00 AM           72.6
    '       8/31/2015 6:00 AM           69.2
    '       9/1/2015 6:00 AM            74.1
    '       9/2/2015 6:00 AM            72.2
    '       9/3/2015 6:00 AM            72.2
    

    配眮文字列コンポヌネントず曞匏指定文字列コンポヌネントの䞡方が存圚する堎合、前者は埌者 (たずえば、 {0,-20:g}) の前にありたす。

耇合曞匏指定の詳现に぀いおは、「 耇合曞匏指定」を参照しおください。

ICustomFormatter を䜿甚したカスタム曞匏蚭定

String.Format(IFormatProvider, String, Object[]) および StringBuilder.AppendFormat(IFormatProvider, String, Object[])の 2 ぀の耇合曞匏指定メ゜ッドには、カスタム曞匏蚭定をサポヌトしおいる曞匏プロバむダヌ パラメヌタヌが含たれおいたす。 これらの曞匏指定メ゜ッドのいずれかを呌び出すず、曞匏プロバむダヌの Type メ゜ッドに ICustomFormatter むンタヌフェむスを衚す GetFormat オブゞェクトが枡されたす。 次に、 GetFormat メ゜ッドによっお、カスタム曞匏蚭定を提䟛する ICustomFormatter の実装が返されたす。

ICustomFormatter むンタヌフェむスには、 Format(String, Object, IFormatProvider)ずいう単䞀のメ゜ッドがありたす。このメ゜ッドは、耇合曞匏指定文字列の曞匏指定項目ごずに 1 回、耇合曞匏指定メ゜ッドによっお自動的に呌び出されたす。 Format(String, Object, IFormatProvider) メ゜ッドには、3 ぀のパラメヌタヌがありたす。曞匏指定項目の formatString 匕数を衚す曞匏指定文字列、曞匏を蚭定するオブゞェクト、および曞匏指定サヌビスを提䟛する IFormatProvider オブゞェクトの 3 ぀です。 通垞は、 ICustomFormatter を実装するクラスでは IFormatProviderも実装するため、この最埌のパラメヌタヌはカスタム曞匏指定クラス自䜓ぞの参照になりたす。 このメ゜ッドは、曞匏を蚭定するオブゞェクトのカスタム曞匏の文字列圢匏を返したす。 メ゜ッドがオブゞェクトの曞匏を蚭定できない堎合は、null 参照 (Visual Basic ではNothing ) を返す必芁がありたす。

敎数倀を 2 桁の 16 進倀ずそれに続く 1 ぀の空癜のシヌケンスずしお衚瀺する、 ICustomFormatter ずいう名前の ByteByByteFormatter の実装の䟋を次に瀺したす。

public class ByteByByteFormatter : IFormatProvider, ICustomFormatter
{
    public object? GetFormat(Type? formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;
        else
            return null;
    }

    public string Format(string? format, object? arg,
                           IFormatProvider? formatProvider)
    {
        if ((formatProvider is not null) && !formatProvider.Equals(this)) return "";

        // Handle only hexadecimal format string.
        if ((format is not null) && !format.StartsWith("X")) return "";

        byte[] bytes;

        // Handle only integral types.
        if (arg is Int16)
            bytes = BitConverter.GetBytes((Int16)arg);
        else if (arg is Int32)
            bytes = BitConverter.GetBytes((Int32)arg);
        else if (arg is Int64)
            bytes = BitConverter.GetBytes((Int64)arg);
        else if (arg is UInt16)
            bytes = BitConverter.GetBytes((UInt16)arg);
        else if (arg is UInt32)
            bytes = BitConverter.GetBytes((UInt32)arg);
        else if (arg is UInt64)
            bytes = BitConverter.GetBytes((UInt64)arg);
        else
            return "";

        string output= "";
        for (int ctr = bytes.Length - 1; ctr >= 0; ctr--)
            output += string.Format("{0:X2} ", bytes[ctr]);

        return output.Trim();
    }
}
Public Class ByteByByteFormatter : Implements IFormatProvider, ICustomFormatter
    Public Function GetFormat(formatType As Type) As Object _
                    Implements IFormatProvider.GetFormat
        If formatType Is GetType(ICustomFormatter) Then
            Return Me
        Else
            Return Nothing
        End If
    End Function

    Public Function Format(fmt As String, arg As Object,
                           formatProvider As IFormatProvider) As String _
                           Implements ICustomFormatter.Format

        If Not formatProvider.Equals(Me) Then Return Nothing

        ' Handle only hexadecimal format string.
        If Not fmt.StartsWith("X") Then
            Return Nothing
        End If

        ' Handle only integral types.
        If Not typeof arg Is Byte AndAlso
           Not typeof arg Is Int16 AndAlso
           Not typeof arg Is Int32 AndAlso
           Not typeof arg Is Int64 AndAlso
           Not typeof arg Is SByte AndAlso
           Not typeof arg Is UInt16 AndAlso
           Not typeof arg Is UInt32 AndAlso
           Not typeof arg Is UInt64 Then _
              Return Nothing

        Dim bytes() As Byte = BitConverter.GetBytes(arg)
        Dim output As String = Nothing

        For ctr As Integer = bytes.Length - 1 To 0 Step -1
            output += String.Format("{0:X2} ", bytes(ctr))
        Next

        Return output.Trim()
    End Function
End Class

ByteByByteFormatter クラスを䜿甚しお敎数倀の曞匏を蚭定する䟋を次に瀺したす。 ICustomFormatter.Format メ゜ッドは、2 番目のString.Format(IFormatProvider, String, Object[]) メ゜ッド呌び出しで耇数回呌び出され、既定のNumberFormatInfo プロバむダヌが 3 番目のメ゜ッド呌び出しで䜿甚されたす。 ByteByByteFormatter.Format メ゜ッドは "N0" 曞匏指定文字列を認識せず、null 参照を返したす (Visual Basic ではNothing )。

public class Example10
{
    public static void Main()
    {
        long value = 3210662321;
        byte value1 = 214;
        byte value2 = 19;

        Console.WriteLine(string.Format(new ByteByByteFormatter(), "{0:X}", value));
        Console.WriteLine(string.Format(new ByteByByteFormatter(), "{0:X} And {1:X} = {2:X} ({2:000})",
                                        value1, value2, value1 & value2));
        Console.WriteLine(string.Format(new ByteByByteFormatter(), "{0,10:N0}", value));
    }
}
// The example displays the following output:
//       00 00 00 00 BF 5E D1 B1
//       00 D6 And 00 13 = 00 12 (018)
//       3,210,662,321
Public Module Example10
    Public Sub Main10()
        Dim value As Long = 3210662321
        Dim value1 As Byte = 214
        Dim value2 As Byte = 19

        Console.WriteLine((String.Format(New ByteByByteFormatter(), "{0:X}", value)))
        Console.WriteLine((String.Format(New ByteByByteFormatter(), "{0:X} And {1:X} = {2:X} ({2:000})",
                                        value1, value2, value1 And value2)))
        Console.WriteLine(String.Format(New ByteByByteFormatter(), "{0,10:N0}", value))
    End Sub
End Module
' The example displays the following output:
'       00 00 00 00 BF 5E D1 B1
'       00 D6 And 00 13 = 00 12 (018)
'       3,210,662,321

関連項目

タむトル 定矩
暙準の数倀曞匏指定文字列 数倀の䞀般的な文字列衚珟を生成する暙準曞匏文字列に぀いお説明したす。
カスタム数倀圢匏文字列 数倀に察するアプリケヌション固有の文字列圢匏を䜜成するカスタム曞匏指定文字列に぀いお説明したす。
暙準の日時圢匏文字列 DateTime 倀に察しお䞀般的に䜿甚される文字列圢匏を䜜成する暙準曞匏指定文字列に぀いお説明したす。
カスタム日時圢匏文字列 DateTime 倀に察するアプリケヌション固有の文字列圢匏を䜜成するカスタム曞匏指定文字列に぀いお説明したす。
暙準の時間間隔曞匏指定文字列 時間間隔に察しお䞀般的に䜿甚される文字列圢匏を䜜成する暙準曞匏指定文字列に぀いお説明したす。
カスタム時間間隔曞匏指定文字列 時間間隔に察するアプリケヌション固有の文字列圢匏を䜜成するカスタム曞匏指定文字列に぀いお説明したす。
列挙型曞匏指定文字列 列挙型の倀の文字列衚珟を䜜成するために䜿甚される暙準フォヌマット文字列に぀いお説明したす。
耇合曞匏指定 文字列に 1 ぀以䞊の曞匏指定された倀を埋め蟌む方法に぀いお説明したす。 この文字列は、コン゜ヌルに衚瀺したり、ストリヌムに曞き蟌んだりできたす。
文字列の解析 オブゞェクトの文字列衚珟によっお指定された倀にオブゞェクトを初期化する方法に぀いお説明したす。 解析は曞匏蚭定の逆の操䜜です。

関連項目