String.Format 方法

定义

将对象的值转换为基于指定格式的字符串,并将其插入到另一个字符串。

如果不熟悉 String.Format 该方法,请参阅 String.Format 方法入门 以获取快速概述。

重载

Format(IFormatProvider, String, Object, Object, Object)

将字符串中的格式项替换为三个指定对象的字符串表示形式。 参数提供区域性特定的格式设置信息。

Format(String, Object, Object, Object)

将字符串中的格式项替换为三个指定对象的字符串表示形式。

Format(IFormatProvider, String, Object, Object)

将字符串中的格式项替换为两个指定对象的字符串表示形式。 参数提供区域性特定的格式设置信息。

Format(String, Object, Object)

将字符串中的格式项替换为两个指定对象的字符串表示形式。

Format(IFormatProvider, CompositeFormat, ReadOnlySpan<Object>)

将 中的 CompositeFormat 格式项替换为指定格式的相应对象的字符串表示形式。

Format(IFormatProvider, String, Object)

将指定字符串中的一个或多个格式项替换为对应对象的字符串表示形式。 参数提供区域性特定的格式设置信息。

Format(IFormatProvider, String, Object[])

将字符串中的格式项替换为指定数组中相应对象的字符串表示形式。 参数提供区域性特定的格式设置信息。

Format(String, Object[])

将指定字符串中的格式项替换为指定数组中相应对象的字符串表示形式。

Format(String, Object)

将字符串中的一个或多个格式项替换为指定对象的字符串表示形式。

Format(IFormatProvider, CompositeFormat, Object[])

将 中的 CompositeFormat 格式项替换为指定格式的相应对象的字符串表示形式。

Format<TArg0,TArg1,TArg2>(IFormatProvider, CompositeFormat, TArg0, TArg1, TArg2)

将 中的 CompositeFormat 格式项替换为指定格式的相应对象的字符串表示形式。

Format<TArg0,TArg1>(IFormatProvider, CompositeFormat, TArg0, TArg1)

将 中的 CompositeFormat 格式项替换为指定格式的相应对象的字符串表示形式。

Format<TArg0>(IFormatProvider, CompositeFormat, TArg0)

将 中的 CompositeFormat 格式项替换为指定格式的相应对象的字符串表示形式。

注解

有关此 API 的详细信息,请参阅 String.Format 的补充 API 说明

Format(IFormatProvider, String, Object, Object, Object)

将字符串中的格式项替换为三个指定对象的字符串表示形式。 参数提供区域性特定的格式设置信息。

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2);
public static string Format (IFormatProvider provider, string format, object arg0, object arg1, object arg2);
public static string Format (IFormatProvider? provider, string format, object? arg0, object? arg1, object? arg2);
static member Format : IFormatProvider * string * obj * obj * obj -> string
Public Shared Function Format (provider As IFormatProvider, format As String, arg0 As Object, arg1 As Object, arg2 As Object) As String

参数

provider
IFormatProvider

一个提供区域性特定的格式设置信息的对象。

arg0
Object

要设置格式的第一个对象。

arg1
Object

要设置格式的第二个对象。

arg2
Object

要设置格式的第三个对象。

返回

format 的副本,其中的格式项已替换为 arg0arg1arg2 的字符串表示形式。

例外

formatnull

format 无效。

格式项的索引小于零,或者大于二。

注解

重要

可以不调用 String.Format 方法或使用复合格式字符串,而改为使用内插字符串(如果受语言支持的话)。 内插字符串是包含内插表达式的字符串。 每个内插表达式都使用表达式的值进行解析,并在分配字符串时包含在结果字符串中。 有关详细信息,请参阅字符串内插(C# 参考)内插字符串(Visual Basic 参考)

此方法使用 复合格式设置功能 将三个表达式转换为其字符串表示形式,并在字符串中嵌入这些表示形式。 在执行转换时, 方法使用区分区域性的格式或自定义格式化程序。 方法通过调用其 ToString (IFormatProvider) 方法将每个Object参数转换为其字符串表示形式,或者,如果对象的相应格式项包含格式字符串,则调用其 ToString (String,IFormatProvider) 方法。 如果这些方法不存在,它将调用对象的无参数 ToString 方法。

但是,在调用 String.Format 方法时,无需关注要调用的特定重载。 相反,可以使用提供区分区域性或自定义格式设置的对象和包含一个或多个格式项的复合格式字符串来调用此方法。 为每个格式项分配一个数字索引;第一个索引从 0 开始。 除了初始字符串,方法调用拥有的额外参数数应该与其拥有的索引值数相同。 例如,格式项有 0 和 1 两个索引的字符串应该有 2 个参数;索引为 0 到 5 的字符串应该有 6 个参数。 然后,语言编译器会将方法调用解析为 方法的特定重载 String.Format

有关使用 String.Format 方法的更详细文档,请参阅 String.Format 方法入门调用哪种方法?

适用于

Format(String, Object, Object, Object)

将字符串中的格式项替换为三个指定对象的字符串表示形式。

public:
 static System::String ^ Format(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2);
public static string Format (string format, object arg0, object arg1, object arg2);
public static string Format (string format, object? arg0, object? arg1, object? arg2);
static member Format : string * obj * obj * obj -> string
Public Shared Function Format (format As String, arg0 As Object, arg1 As Object, arg2 As Object) As String

参数

arg0
Object

要设置格式的第一个对象。

arg1
Object

要设置格式的第二个对象。

arg2
Object

要设置格式的第三个对象。

返回

format 的副本,其中的格式项已替换为 arg0arg1arg2 的字符串表示形式。

例外

formatnull

format 无效。

格式项的索引小于零,或者大于二。

注解

重要

可以不调用 String.Format 方法或使用复合格式字符串,而改为使用内插字符串(如果受语言支持的话)。 内插字符串是包含内插表达式的字符串。 每个内插表达式都使用表达式的值进行解析,并在分配字符串时包含在结果字符串中。 有关详细信息,请参阅字符串内插(C# 参考)内插字符串(Visual Basic 参考)

此方法使用 复合格式设置功能 将三个表达式的值转换为其字符串表示形式,并在字符串中嵌入这些表示形式。

但是,在调用 String.Format 方法时,无需关注要调用的特定重载。 相反,可以借助包括一个或多个格式项的复合格式字符串调用方法。 为每个格式项分配一个数字索引;第一个索引从 0 开始。 除了初始字符串,方法调用拥有的额外参数数应该与其拥有的索引值数相同。 例如,格式项有 0 和 1 两个索引的字符串应该有 2 个参数;索引为 0 到 5 的字符串应该有 6 个参数。 然后,语言编译器会将方法调用解析为 方法的特定重载 String.Format

有关使用 String.Format 方法的更详细文档,请参阅 String.Format 方法入门调用哪种方法?

示例:设置三个参数的格式

此示例使用 Format(String, Object, Object, Object) 方法创建一个字符串,该字符串演示具有两个整数值的布尔 And 运算的结果。 请注意,格式字符串包含六个格式项,但方法的参数列表中只有三个项,因为每个项的格式有两种不同的方式。

using namespace System;

void main()
{
   String^ formatString = "    {0,10} ({0,8:X8})\n" + 
                           "And {1,10} ({1,8:X8})\n" + 
                           "  = {2,10} ({2,8:X8})";
   int value1 = 16932;
   int value2 = 15421;
   String^ result = String::Format(formatString, 
                                   value1, value2, value1 & value2);
   Console::WriteLine(result);
}
// The example displays the following output:
//                16932 (00004224)
//       And      15421 (00003C3D)
//         =         36 (00000024)
string formatString = "    {0,10} ({0,8:X8})\n" + 
                      "And {1,10} ({1,8:X8})\n" + 
                      "  = {2,10} ({2,8:X8})";
int value1 = 16932;
int value2 = 15421;
string result = String.Format(formatString, 
                              value1, value2, value1 & value2);
Console.WriteLine(result);
// The example displays the following output:
//                16932 (00004224)
//       And      15421 (00003C3D)
//         =         36 (00000024)
open System

let formatString = 
    "    {0,10} ({0,8:X8})\nAnd {1,10} ({1,8:X8})\n  = {2,10} ({2,8:X8})"

let value1 = 16932
let value2 = 15421
String.Format(formatString, value1, value2, value1 &&& value2)
|> printfn "%s"
// The example displays the following output:
//                16932 (00004224)
//       And      15421 (00003C3D)
//         =         36 (00000024)
Public Module Example
   Public Sub Main()
      Dim formatString As String = "    {0,10} ({0,8:X8})" + vbCrLf +  _
                                   "And {1,10} ({1,8:X8})" + vbCrLf + _
                                   "  = {2,10} ({2,8:X8})"
      Dim value1 As Integer = 16932
      Dim value2 As Integer = 15421
      Dim result As String = String.Format(formatString, _
                                           value1, value2, value1 And value2)
      Console.WriteLine(result)                          
   End Sub
End Module
' The example displays the following output:
'                16932 (00004224)
'       And      15421 (00003C3D)
'         =         36 (00000024)

另请参阅

适用于

Format(IFormatProvider, String, Object, Object)

将字符串中的格式项替换为两个指定对象的字符串表示形式。 参数提供区域性特定的格式设置信息。

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0, System::Object ^ arg1);
public static string Format (IFormatProvider provider, string format, object arg0, object arg1);
public static string Format (IFormatProvider? provider, string format, object? arg0, object? arg1);
static member Format : IFormatProvider * string * obj * obj -> string
Public Shared Function Format (provider As IFormatProvider, format As String, arg0 As Object, arg1 As Object) As String

参数

provider
IFormatProvider

一个提供区域性特定的格式设置信息的对象。

arg0
Object

要设置格式的第一个对象。

arg1
Object

要设置格式的第二个对象。

返回

format 的副本,其中的格式项替换为 arg0arg1 的字符串表示形式。

例外

formatnull

format 无效。

格式项的索引不为零或一。

注解

重要

可以不调用 String.Format 方法或使用复合格式字符串,而改为使用内插字符串(如果受语言支持的话)。 内插字符串是包含内插表达式的字符串。 每个内插表达式都使用表达式的值进行解析,并在分配字符串时包含在结果字符串中。 有关详细信息,请参阅字符串内插(C# 参考)内插字符串(Visual Basic 参考)

此方法使用 复合格式设置功能 将两个表达式转换为其字符串表示形式,并在字符串中嵌入这些表示形式。 在执行转换时, 方法使用区分区域性的格式或自定义格式化程序。 方法通过调用其 ToString (IFormatProvider) 方法将每个Object参数转换为其字符串表示形式,或者,如果对象的相应格式项包含格式字符串,则调用其 ToString (String,IFormatProvider) 方法。 如果这些方法不存在,它将调用对象的无参数 ToString 方法。

但是,在调用 String.Format 方法时,无需关注要调用的特定重载。 相反,可以使用提供区分区域性或自定义格式设置的对象和包含一个或多个格式项的复合格式字符串来调用此方法。 为每个格式项分配一个数字索引;第一个索引从 0 开始。 除了初始字符串,方法调用拥有的额外参数数应该与其拥有的索引值数相同。 例如,格式项有 0 和 1 两个索引的字符串应该有 2 个参数;索引为 0 到 5 的字符串应该有 6 个参数。 然后,语言编译器会将方法调用解析为 方法的特定重载 String.Format

有关使用 String.Format 方法的更详细文档,请参阅 String.Format 方法入门调用哪种方法?

适用于

Format(String, Object, Object)

将字符串中的格式项替换为两个指定对象的字符串表示形式。

public:
 static System::String ^ Format(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1);
public static string Format (string format, object arg0, object arg1);
public static string Format (string format, object? arg0, object? arg1);
static member Format : string * obj * obj -> string
Public Shared Function Format (format As String, arg0 As Object, arg1 As Object) As String

参数

arg0
Object

要设置格式的第一个对象。

arg1
Object

要设置格式的第二个对象。

返回

format 的副本,其中的格式项替换为 arg0arg1 的字符串表示形式。

例外

formatnull

format 无效。

格式项的索引不为零或一。

注解

重要

可以不调用 String.Format 方法或使用复合格式字符串,而改为使用内插字符串(如果受语言支持的话)。 内插字符串是包含内插表达式的字符串。 每个内插表达式都使用表达式的值进行解析,并在分配字符串时包含在结果字符串中。 有关详细信息,请参阅字符串内插(C# 参考)内插字符串(Visual Basic 参考)

此方法使用 复合格式设置功能 将两个表达式的值转换为其字符串表示形式,并在字符串中嵌入这些表示形式。

但是,在调用 String.Format 方法时,无需关注要调用的特定重载。 相反,可以借助包括一个或多个格式项的复合格式字符串调用方法。 为每个格式项分配一个数字索引;第一个索引从 0 开始。 除了初始字符串,方法调用拥有的额外参数数应该与其拥有的索引值数相同。 例如,格式项有 0 和 1 两个索引的字符串应该有 2 个参数;索引为 0 到 5 的字符串应该有 6 个参数。 然后,语言编译器会将方法调用解析为 方法的特定重载 String.Format

有关使用 String.Format 方法的更详细文档,请参阅 String.Format 方法入门调用哪种方法?

示例:设置两个参数的格式

此示例使用 Format(String, Object, Object) 方法显示存储在泛型 Dictionary<TKey,TValue> 对象中的时间和温度数据。 请注意,格式字符串有三个格式项,尽管只有两个对象需要格式化。 这是因为列表中的第一个对象 (日期和时间值) 由两个格式项使用:第一个格式项显示时间,第二个显示日期。

using namespace System;
using namespace System::Collections::Generic;

void main()
{
   Dictionary<DateTime, Double>^ temperatureInfo = gcnew Dictionary<DateTime, Double>(); 
   temperatureInfo->Add(DateTime(2010, 6, 1, 14, 0, 0), 87.46);
   temperatureInfo->Add(DateTime(2010, 12, 1, 10, 0, 0), 36.81);
      
   Console::WriteLine("Temperature Information:\n");
   String^ output;   
   for each (KeyValuePair<DateTime, Double>^ item in temperatureInfo)
   {
      output = String::Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}�F", 
                              item->Key, item->Value);
      Console::WriteLine(output);
   }
}
// The example displays the following output:
//       Temperature Information:
//       
//       Temperature at  2:00 PM on  6/1/2010:  87.5�F
//       Temperature at 10:00 AM on 12/1/2010:  36.8�F
Dictionary<DateTime, Double> temperatureInfo = new Dictionary<DateTime, Double>(); 
temperatureInfo.Add(new DateTime(2010, 6, 1, 14, 0, 0), 87.46);
temperatureInfo.Add(new DateTime(2010, 12, 1, 10, 0, 0), 36.81);

Console.WriteLine("Temperature Information:\n");
string output;   
foreach (var item in temperatureInfo)
{
   output = String.Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F", 
                          item.Key, item.Value);
   Console.WriteLine(output);
}
// The example displays output like the following:
//       Temperature Information:
//       
//       Temperature at  2:00 PM on  6/1/2010:  87.5°F
//       Temperature at 10:00 AM on 12/1/2010:  36.8°F
open System
open System.Collections.Generic

let temperatureInfo = Dictionary<DateTime, float>() 
temperatureInfo.Add(DateTime(2010, 6, 1, 14, 0, 0), 87.46)
temperatureInfo.Add(DateTime(2010, 12, 1, 10, 0, 0), 36.81)

printfn $"Temperature Information:\n"
for item in temperatureInfo do
   String.Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F", item.Key, item.Value)
   |> printfn "%s"
// The example displays output like the following:
//       Temperature Information:
//       
//       Temperature at  2:00 PM on  6/1/2010:  87.5°F
//       Temperature at 10:00 AM on 12/1/2010:  36.8°F
Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim temperatureInfo As New Dictionary(Of Date, Double) 
      temperatureInfo.Add(#6/1/2010 2:00PM#, 87.46)
      temperatureInfo.Add(#12/1/2010 10:00AM#, 36.81)
      
      Console.WriteLine("Temperature Information:")
      Console.WriteLine()
      Dim output As String   
      For Each item In temperatureInfo
         output = String.Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F", _
                                item.Key, item.Value)
         Console.WriteLine(output)
      Next
   End Sub
End Module
' The example displays the following output:
'       Temperature Information:
'       
'       Temperature at  2:00 PM on  6/1/2010:  87.5°F
'       Temperature at 10:00 AM on 12/1/2010:  36.8°F

另请参阅

适用于

Format(IFormatProvider, CompositeFormat, ReadOnlySpan<Object>)

将 中的 CompositeFormat 格式项替换为指定格式的相应对象的字符串表示形式。

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::Text::CompositeFormat ^ format, ReadOnlySpan<System::Object ^> args);
public static string Format (IFormatProvider? provider, System.Text.CompositeFormat format, ReadOnlySpan<object?> args);
static member Format : IFormatProvider * System.Text.CompositeFormat * ReadOnlySpan<obj> -> string
Public Shared Function Format (provider As IFormatProvider, format As CompositeFormat, args As ReadOnlySpan(Of Object)) As String

参数

provider
IFormatProvider

一个提供区域性特定的格式设置信息的对象。

format
CompositeFormat

一个 CompositeFormat

args
ReadOnlySpan<Object>

要设置格式的对象范围。

返回

格式化的字符串。

例外

formatnull

格式项的索引大于或等于提供的参数数。

适用于

Format(IFormatProvider, String, Object)

将指定字符串中的一个或多个格式项替换为对应对象的字符串表示形式。 参数提供区域性特定的格式设置信息。

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0);
public static string Format (IFormatProvider provider, string format, object arg0);
public static string Format (IFormatProvider? provider, string format, object? arg0);
static member Format : IFormatProvider * string * obj -> string
Public Shared Function Format (provider As IFormatProvider, format As String, arg0 As Object) As String

参数

provider
IFormatProvider

一个提供区域性特定的格式设置信息的对象。

arg0
Object

要设置格式的对象。

返回

format 的副本,其中的一个或多个格式项已替换为 arg0 的字符串表示形式。

例外

formatnull

format 无效。

格式项的索引不为零。

注解

重要

可以不调用 String.Format 方法或使用复合格式字符串,而改为使用内插字符串(如果受语言支持的话)。 内插字符串是包含内插表达式的字符串。 每个内插表达式都使用表达式的值进行解析,并在分配字符串时包含在结果字符串中。 有关详细信息,请参阅字符串内插(C# 参考)内插字符串(Visual Basic 参考)

此方法使用 复合格式设置功能 将表达式的值转换为其字符串表示形式,并在字符串中嵌入该表示形式。 在执行转换时, 方法使用区分区域性的格式或自定义格式化程序。 方法通过调用其 ToString (IFormatProvider) 方法转换为arg0字符串表示形式,或者,如果对象的相应格式项包含格式字符串,则调用其 ToString (String,IFormatProvider) 方法。 如果这些方法不存在,它将调用对象的无参数 ToString 方法。

但是,在调用 String.Format 方法时,无需关注要调用的特定重载。 相反,可以使用提供区分区域性或自定义格式设置的对象和包含一个或多个格式项的复合格式字符串来调用此方法。 为每个格式项分配一个数字索引;第一个索引从 0 开始。 除了初始字符串,方法调用拥有的额外参数数应该与其拥有的索引值数相同。 例如,格式项有 0 和 1 两个索引的字符串应该有 2 个参数;索引为 0 到 5 的字符串应该有 6 个参数。 然后,语言编译器会将方法调用解析为 方法的特定重载 String.Format

有关使用 String.Format 方法的更详细文档,请参阅 String.Format 方法入门调用哪种方法?

适用于

Format(IFormatProvider, String, Object[])

将字符串中的格式项替换为指定数组中相应对象的字符串表示形式。 参数提供区域性特定的格式设置信息。

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, ... cli::array <System::Object ^> ^ args);
public static string Format (IFormatProvider provider, string format, params object[] args);
public static string Format (IFormatProvider? provider, string format, params object?[] args);
static member Format : IFormatProvider * string * obj[] -> string
Public Shared Function Format (provider As IFormatProvider, format As String, ParamArray args As Object()) As String

参数

provider
IFormatProvider

一个提供区域性特定的格式设置信息的对象。

args
Object[]

一个对象数组,其中包含零个或多个要设置格式的对象。

返回

format 的副本,其中格式项已替换为 args 中相应对象的字符串表示形式。

例外

formatargsnull

format 无效。

格式项的索引小于零,或者大于或等于 args 数组的长度。

注解

重要

可以不调用 String.Format 方法或使用复合格式字符串,而改为使用内插字符串(如果受语言支持的话)。 内插字符串是包含内插表达式的字符串。 每个内插表达式都使用表达式的值进行解析,并在分配字符串时包含在结果字符串中。 有关详细信息,请参阅字符串内插(C# 参考)内插字符串(Visual Basic 参考)

此方法使用 复合格式设置功能 将四个或更多个表达式转换为其字符串表示形式,并在字符串中嵌入这些表示形式。 在执行转换时, 方法使用区分区域性的格式或自定义格式化程序。 方法通过调用其 ToString (IFormatProvider) 方法将每个Object参数转换为其字符串表示形式,或者,如果对象的相应格式项包含格式字符串,则调用其 ToString (String,IFormatProvider) 方法。 如果这些方法不存在,它将调用对象的无参数 ToString 方法。

但是,在调用 String.Format 方法时,无需关注要调用的特定重载。 相反,可以使用提供区分区域性或自定义格式设置的对象和包含一个或多个格式项的复合格式字符串来调用此方法。 为每个格式项分配一个数字索引;第一个索引从 0 开始。 除了初始字符串,方法调用拥有的额外参数数应该与其拥有的索引值数相同。 例如,格式项有 0 和 1 两个索引的字符串应该有 2 个参数;索引为 0 到 5 的字符串应该有 6 个参数。 然后,语言编译器会将方法调用解析为 方法的特定重载 String.Format

有关使用 String.Format 方法的更详细文档,请参阅 String.Format 方法入门调用哪种方法?

示例:区分区域性的格式

此示例使用 Format(IFormatProvider, String, Object[]) 方法通过多个不同的区域性显示某些日期和时间值以及数值的字符串表示形式。

string[] cultureNames = { "en-US", "fr-FR", "de-DE", "es-ES" };

DateTime dateToDisplay = new DateTime(2009, 9, 1, 18, 32, 0);
double value = 9164.32;

Console.WriteLine("Culture     Date                                Value\n");
foreach (string cultureName in cultureNames)
{
   System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(cultureName);
   string output = String.Format(culture, "{0,-11} {1,-35:D} {2:N}", 
                                 culture.Name, dateToDisplay, value);
   Console.WriteLine(output);
}    
// The example displays the following output:
//    Culture     Date                                Value
//    
//    en-US       Tuesday, September 01, 2009         9,164.32
//    fr-FR       mardi 1 septembre 2009              9 164,32
//    de-DE       Dienstag, 1. September 2009         9.164,32
//    es-ES       martes, 01 de septiembre de 2009    9.164,32
open System
open System.Globalization

let cultureNames = [| "en-US"; "fr-FR"; "de-DE"; "es-ES" |]

let dateToDisplay = DateTime(2009, 9, 1, 18, 32, 0)
let value = 9164.32

printfn "Culture     Date                                Value\n"
for cultureName in cultureNames do
    let culture = CultureInfo cultureName
    String.Format(culture, "{0,-11} {1,-35:D} {2:N}", culture.Name, dateToDisplay, value)
    |> printfn "%s"
// The example displays the following output:
//    Culture     Date                                Value
//    
//    en-US       Tuesday, September 01, 2009         9,164.32
//    fr-FR       mardi 1 septembre 2009              9 164,32
//    de-DE       Dienstag, 1. September 2009         9.164,32
//    es-ES       martes, 01 de septiembre de 2009    9.164,32
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim cultureNames() As String = { "en-US", "fr-FR", "de-DE", "es-ES" }
      
      Dim dateToDisplay As Date = #9/1/2009 6:32PM#
      Dim value As Double = 9164.32

      Console.WriteLine("Culture     Date                                Value")
      Console.WriteLine()      
      For Each cultureName As String In cultureNames
         Dim culture As New CultureInfo(cultureName)
         Dim output As String = String.Format(culture, "{0,-11} {1,-35:D} {2:N}", _
                                              culture.Name, dateToDisplay, value)
         Console.WriteLine(output)
      Next    
   End Sub
End Module
' The example displays the following output:
'       Culture     Date                                Value
'       
'       en-US       Tuesday, September 01, 2009         9,164.32
'       fr-FR       mardi 1 septembre 2009              9 164,32
'       de-DE       Dienstag, 1. September 2009         9.164,32
'       es-ES       martes, 01 de septiembre de 2009    9.164,32

另请参阅

适用于

Format(String, Object[])

将指定字符串中的格式项替换为指定数组中相应对象的字符串表示形式。

public:
 static System::String ^ Format(System::String ^ format, ... cli::array <System::Object ^> ^ args);
public static string Format (string format, params object[] args);
public static string Format (string format, params object?[] args);
static member Format : string * obj[] -> string
Public Shared Function Format (format As String, ParamArray args As Object()) As String

参数

args
Object[]

一个对象数组,其中包含零个或多个要设置格式的对象。

返回

format 的副本,其中格式项已替换为 args 中相应对象的字符串表示形式。

例外

formatargsnull

format 无效。

格式项的索引小于零,或者大于或等于 args 数组的长度。

注解

重要

可以不调用 String.Format 方法或使用复合格式字符串,而改为使用内插字符串(如果受语言支持的话)。 内插字符串是包含内插表达式的字符串。 每个内插表达式都使用表达式的值进行解析,并在分配字符串时包含在结果字符串中。 有关详细信息,请参阅字符串内插(C# 参考)内插字符串(Visual Basic 参考)

此方法使用 复合格式设置功能 将四个或更多表达式的值转换为其字符串表示形式,并在字符串中嵌入这些表示形式。 args由于 参数标有 System.ParamArrayAttribute 特性,因此可以将 对象作为单个参数或Object数组传递给 方法。

但是,在调用 String.Format 方法时,无需关注要调用的特定重载。 相反,可以借助包括一个或多个格式项的复合格式字符串调用方法。 为每个格式项分配一个数字索引;第一个索引从 0 开始。 除了初始字符串,方法调用拥有的额外参数数应该与其拥有的索引值数相同。 例如,格式项有 0 和 1 两个索引的字符串应该有 2 个参数;索引为 0 到 5 的字符串应该有 6 个参数。 然后,语言编译器会将方法调用解析为 方法的特定重载 String.Format

有关使用 String.Format 方法的更详细文档,请参阅 String.Format 方法入门调用哪种方法?

示例:设置三个以上参数的格式

此示例创建一个字符串,其中包含特定日期的高温和低温数据。 复合格式字符串在 C# 示例中有五个格式项,在 Visual Basic 示例中有六个格式项。 其中两个格式项定义其相应值字符串表示形式的宽度,第一个格式项还包括标准日期和时间格式字符串。

using namespace System;

void main()
{
   DateTime date1 = DateTime(2009, 7, 1);
   TimeSpan hiTime = TimeSpan(14, 17, 32);
   Decimal hiTemp = (Decimal) 62.1; 
   TimeSpan loTime = TimeSpan(3, 16, 10);
   Decimal loTemp = (Decimal)54.8; 

   String^ result1 = String::Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", 
                                    date1, hiTime, hiTemp, loTime, loTemp);
   Console::WriteLine(result1);
   Console::WriteLine();
           
   String^ result2 = String::Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", 
                                    gcnew array<Object^> { date1, hiTime, hiTemp, loTime, loTemp });
   Console::WriteLine(result2);
}
// The example displays the following output:
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
DateTime date1 = new DateTime(2009, 7, 1);
TimeSpan hiTime = new TimeSpan(14, 17, 32);
decimal hiTemp = 62.1m; 
TimeSpan loTime = new TimeSpan(3, 16, 10);
decimal loTemp = 54.8m; 

string result1 = String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", 
                               date1, hiTime, hiTemp, loTime, loTemp);
Console.WriteLine(result1);
Console.WriteLine();
     
string result2 = String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", 
                               new object[] { date1, hiTime, hiTemp, loTime, loTemp });
Console.WriteLine(result2);
// The example displays output like the following:
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
let date1 = DateTime(2009, 7, 1)
let hiTime = TimeSpan(14, 17, 32)
let hiTemp = 62.1m 
let loTime = TimeSpan(3, 16, 10)
let loTemp = 54.8m 

String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", date1, hiTime, hiTemp, loTime, loTemp)
|> printfn "%s\n"
      
String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", [| date1 :> obj; hiTime; hiTemp; loTime; loTemp |])
|> printfn "%s"
// The example displays output like the following:
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
//       Temperature on 7/1/2009:
//          14:17:32: 62.1 degrees (hi)
//          03:16:10: 54.8 degrees (lo)
Module Example
   Public Sub Main()
      Dim date1 As Date = #7/1/2009#
      Dim hiTime As New TimeSpan(14, 17, 32)
      Dim hiTemp As Decimal = 62.1d 
      Dim loTime As New TimeSpan(3, 16, 10)
      Dim loTemp As Decimal = 54.8d 

      Dim result1 As String = String.Format("Temperature on {0:d}:{5}{1,11}: {2} degrees (hi){5}{3,11}: {4} degrees (lo)", _
                                           date1, hiTime, hiTemp, loTime, loTemp, vbCrLf)
      Console.WriteLine(result1)
      Console.WriteLine()
           
      Dim result2 As String = String.Format("Temperature on {0:d}:{5}{1,11}: {2} degrees (hi){5}{3,11}: {4} degrees (lo)", _
                                            New Object() { date1, hiTime, hiTemp, loTime, loTemp, vbCrLf })
      Console.WriteLine(result2)                                            
   End Sub
End Module
' The example displays the following output:
'       Temperature on 7/1/2009:
'          14:17:32: 62.1 degrees (hi)
'          03:16:10: 54.8 degrees (lo)
'
'       Temperature on 7/1/2009:
'          14:17:32: 62.1 degrees (hi)
'          03:16:10: 54.8 degrees (lo)

还可以传递要格式化为数组而不是参数列表的对象。

using namespace System;

ref class CityInfo
{
public:
   CityInfo(String^ name, int population, Decimal area, int year)
   {
      this->Name = name;
      this->Population = population;
      this->Area = area;
      this->Year = year;
   }
   
   String^ Name; 
   int Population;
   Decimal Area;
   int Year;
};

ref class Example
{
public:
   static void ShowPopulationData(CityInfo^ city)
   {
      array<Object^>^ args = gcnew array<Object^> { city->Name, city->Year, city->Population, city->Area };
      String^ result = String::Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet", 
                                    args);
      Console::WriteLine(result); 
   }
};

void main()
{
   CityInfo^ nyc2010 = gcnew CityInfo("New York", 8175133, (Decimal) 302.64, 2010);
   Example::ShowPopulationData(nyc2010);
   CityInfo^ sea2010 = gcnew CityInfo("Seattle", 608660, (Decimal) 83.94, 2010);      
   Example::ShowPopulationData(sea2010); 
}
// The example displays the following output:
//       New York in 2010: Population 8,175,133, Area 302.6 sq. feet
//       Seattle in 2010: Population 608,660, Area 83.9 sq. feet
using System;

public class CityInfo
{
   public CityInfo(String name, int population, Decimal area, int year)
   {
      this.Name = name;
      this.Population = population;
      this.Area = area;
      this.Year = year;
   }
   
   public readonly String Name; 
   public readonly int Population;
   public readonly Decimal Area;
   public readonly int Year;
}

public class Example
{
   public static void Main()
   {
      CityInfo nyc2010 = new CityInfo("New York", 8175133, 302.64m, 2010);
      ShowPopulationData(nyc2010);
      CityInfo sea2010 = new CityInfo("Seattle", 608660, 83.94m, 2010);      
      ShowPopulationData(sea2010); 
   }

   private static void ShowPopulationData(CityInfo city)
   {
      object[] args = { city.Name, city.Year, city.Population, city.Area };
      String result = String.Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet", 
                                    args);
      Console.WriteLine(result); 
   }
}
// The example displays the following output:
//       New York in 2010: Population 8,175,133, Area 302.6 sq. feet
//       Seattle in 2010: Population 608,660, Area 83.9 sq. feet
open System

type CityInfo =
  { Name: string
    Population: int
    Area: Decimal
    Year: int }

let showPopulationData city =
    let args: obj[] = [| city.Name; city.Year; city.Population; city.Area |]
    String.Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet", args)
    |> printfn "%s"

{ Name = "New York"; Population = 8175133; Area = 302.64m; Year = 2010 }
|> showPopulationData

 
{ Name = "Seattle"; Population = 608660; Area = 83.94m; Year = 2010 }      
|> showPopulationData 

// The example displays the following output:
//       New York in 2010: Population 8,175,133, Area 302.6 sq. feet
//       Seattle in 2010: Population 608,660, Area 83.9 sq. feet
Public Class CityInfo
   Public Sub New(name As String, population As Integer, area As Decimal, year As Integer)
      Me.Name = name
      Me.Population = population
      Me.Area = area
      Me.Year = year
   End Sub
   
   Public ReadOnly Name As String
   Public ReadOnly Population As Integer
   Public ReadOnly Area As Decimal
   Public ReadOnly Year As Integer
End Class

Module Example
   Public Sub Main()
      Dim nyc2010 As New CityInfo("New York", 8175133, 302.64d, 2010)
      ShowPopulationData(nyc2010)
      Dim sea2010 As New CityInfo("Seattle", 608660, 83.94d, 2010)      
      ShowPopulationData(sea2010) 
   End Sub
   
   Private Sub ShowPopulationData(city As CityInfo)
      Dim args() As Object = { city.Name, city.Year, city.Population, city.Area }
      Dim result = String.Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet", args)
      Console.WriteLine(result) 
   End Sub
End Module
' The example displays the following output:
'       New York in 2010: Population 8,175,133, Area 302.6 sq. feet
'       Seattle in 2010: Population 608,660, Area 83.9 sq. feet

另请参阅

适用于

Format(String, Object)

将字符串中的一个或多个格式项替换为指定对象的字符串表示形式。

public:
 static System::String ^ Format(System::String ^ format, System::Object ^ arg0);
public static string Format (string format, object arg0);
public static string Format (string format, object? arg0);
static member Format : string * obj -> string
Public Shared Function Format (format As String, arg0 As Object) As String

参数

arg0
Object

要设置格式的对象。

返回

format 的副本,其中的任何格式项均替换为 arg0 的字符串表示形式。

例外

formatnull

format 中的格式项无效。

格式项的索引不为零。

注解

重要

可以不调用 String.Format 方法或使用复合格式字符串,而改为使用内插字符串(如果受语言支持的话)。 内插字符串是包含内插表达式的字符串。 每个内插表达式都使用表达式的值进行解析,并在分配字符串时包含在结果字符串中。 有关详细信息,请参阅字符串内插(C# 参考)内插字符串(Visual Basic 参考)

此方法使用 复合格式设置功能 将表达式的值转换为其字符串表示形式,并在字符串中嵌入该表示形式。

但是,在调用 String.Format 方法时,无需关注要调用的特定重载。 相反,可以借助包括一个或多个格式项的复合格式字符串调用方法。 为每个格式项分配一个数字索引;第一个索引从 0 开始。 除了初始字符串,方法调用拥有的额外参数数应该与其拥有的索引值数相同。 例如,格式项有 0 和 1 两个索引的字符串应该有 2 个参数;索引为 0 到 5 的字符串应该有 6 个参数。 然后,语言编译器会将方法调用解析为 方法的特定重载 String.Format

有关使用 String.Format 方法的更详细文档,请参阅 String.Format 方法入门调用哪种方法?

示例:设置单个参数的格式

以下示例使用 Format(String, Object) 方法在字符串中间嵌入个人的年龄。

using namespace System;

void main()
{
   DateTime birthdate = DateTime(1993, 7, 28);
   array<DateTime>^ dates = gcnew array<DateTime> { DateTime(1993, 8, 16), 
                                                    DateTime(1994, 7, 28), 
                                                    DateTime(2000, 10, 16), 
                                                    DateTime(2003, 7, 27), 
                                                    DateTime(2007, 5, 27) };

   for each (DateTime dateValue in dates)
   {
      TimeSpan interval = dateValue - birthdate;
      // Get the approximate number of years, without accounting for leap years.
      int years = ((int)interval.TotalDays) / 365;
      // See if adding the number of years exceeds dateValue.
      String^ output;
      if (birthdate.AddYears(years) <= dateValue) {
         output = String::Format("You are now {0} years old.", years);
         Console::WriteLine(output);
      }   
      else {
         output = String::Format("You are now {0} years old.", years - 1);
         Console::WriteLine(output);
      }      
   }
}
// The example displays the following output:
//       You are now 0 years old.
//       You are now 1 years old.
//       You are now 7 years old.
//       You are now 9 years old.
//       You are now 13 years old.
DateTime birthdate = new DateTime(1993, 7, 28);
DateTime[] dates = { new DateTime(1993, 8, 16), 
                     new DateTime(1994, 7, 28), 
                     new DateTime(2000, 10, 16), 
                     new DateTime(2003, 7, 27), 
                     new DateTime(2007, 5, 27) };

foreach (DateTime dateValue in dates)
{
   TimeSpan interval = dateValue - birthdate;
   // Get the approximate number of years, without accounting for leap years.
   int years = ((int) interval.TotalDays) / 365;
   // See if adding the number of years exceeds dateValue.
   string output;
   if (birthdate.AddYears(years) <= dateValue) {
      output = String.Format("You are now {0} years old.", years);
      Console.WriteLine(output);
   }   
   else {
      output = String.Format("You are now {0} years old.", years - 1);
      Console.WriteLine(output);
   }      
}
// The example displays the following output:
//       You are now 0 years old.
//       You are now 1 years old.
//       You are now 7 years old.
//       You are now 9 years old.
//       You are now 13 years old.
let birthdate = DateTime(1993, 7, 28)
let dates = 
    [ DateTime(1993, 8, 16) 
      DateTime(1994, 7, 28)
      DateTime(2000, 10, 16)
      DateTime(2003, 7, 27)
      DateTime(2007, 5, 27) ]

for dateValue in dates do
    let interval = dateValue - birthdate
    // Get the approximate number of years, without accounting for leap years.
    let years = (int interval.TotalDays) / 365
    // See if adding the number of years exceeds dateValue.
    if birthdate.AddYears years <= dateValue then
        String.Format("You are now {0} years old.", years)
    else
        String.Format("You are now {0} years old.", years - 1)
    |> printfn "%s"
// The example displays the following output:
//       You are now 0 years old.
//       You are now 1 years old.
//       You are now 7 years old.
//       You are now 9 years old.
//       You are now 13 years old.
Module Example
   Public Sub Main()
      Dim birthdate As Date = #7/28/1993#
      Dim dates() As Date = { #9/16/1993#, #7/28/1994#, #10/16/2000#, _
                              #7/27/2003#, #5/27/2007# }
      For Each dateValue As Date In dates
         Dim interval As TimeSpan = dateValue - birthdate
         ' Get the approximate number of years, without accounting for leap years.
         Dim years As Integer = CInt(interval.TotalDays) \ 365
         ' See if adding the number of years exceeds dateValue.
         Dim output As String
         If birthdate.AddYears(years) <= dateValue Then
            output = String.Format("You are now {0} years old.", years)
            Console.WriteLine(output)
         Else
            output = String.Format("You are now {0} years old.", years - 1)
            Console.WriteLine(output)   
         End If
      Next
   End Sub
End Module
' The example displays the following output:
'       You are now 0 years old.
'       You are now 1 years old.
'       You are now 7 years old.
'       You are now 9 years old.
'       You are now 13 years old.

另请参阅

适用于

Format(IFormatProvider, CompositeFormat, Object[])

将 中的 CompositeFormat 格式项替换为指定格式的相应对象的字符串表示形式。

public:
 static System::String ^ Format(IFormatProvider ^ provider, System::Text::CompositeFormat ^ format, ... cli::array <System::Object ^> ^ args);
public static string Format (IFormatProvider? provider, System.Text.CompositeFormat format, params object?[] args);
static member Format : IFormatProvider * System.Text.CompositeFormat * obj[] -> string
Public Shared Function Format (provider As IFormatProvider, format As CompositeFormat, ParamArray args As Object()) As String

参数

provider
IFormatProvider

一个提供区域性特定的格式设置信息的对象。

format
CompositeFormat

一个 CompositeFormat

args
Object[]

要设置其格式的对象的数组。

返回

格式化的字符串。

例外

formatargsnull

格式项的索引大于或等于提供的参数数。

适用于

Format<TArg0,TArg1,TArg2>(IFormatProvider, CompositeFormat, TArg0, TArg1, TArg2)

将 中的 CompositeFormat 格式项替换为指定格式的相应对象的字符串表示形式。

public:
generic <typename TArg0, typename TArg1, typename TArg2>
 static System::String ^ Format(IFormatProvider ^ provider, System::Text::CompositeFormat ^ format, TArg0 arg0, TArg1 arg1, TArg2 arg2);
public static string Format<TArg0,TArg1,TArg2> (IFormatProvider? provider, System.Text.CompositeFormat format, TArg0 arg0, TArg1 arg1, TArg2 arg2);
static member Format : IFormatProvider * System.Text.CompositeFormat * 'TArg0 * 'TArg1 * 'TArg2 -> string
Public Shared Function Format(Of TArg0, TArg1, TArg2) (provider As IFormatProvider, format As CompositeFormat, arg0 As TArg0, arg1 As TArg1, arg2 As TArg2) As String

类型参数

TArg0

要设置格式的第一个对象的类型。

TArg1

要设置格式的第二个对象的类型。

TArg2

要设置格式的第三个对象的类型。

参数

provider
IFormatProvider

一个提供区域性特定的格式设置信息的对象。

format
CompositeFormat

一个 CompositeFormat

arg0
TArg0

要设置格式的第一个对象。

arg1
TArg1

要设置格式的第二个对象。

arg2
TArg2

要设置格式的第三个对象。

返回

格式化的字符串。

例外

formatnull

格式项的索引大于或等于提供的参数数。

适用于

Format<TArg0,TArg1>(IFormatProvider, CompositeFormat, TArg0, TArg1)

将 中的 CompositeFormat 格式项替换为指定格式的相应对象的字符串表示形式。

public:
generic <typename TArg0, typename TArg1>
 static System::String ^ Format(IFormatProvider ^ provider, System::Text::CompositeFormat ^ format, TArg0 arg0, TArg1 arg1);
public static string Format<TArg0,TArg1> (IFormatProvider? provider, System.Text.CompositeFormat format, TArg0 arg0, TArg1 arg1);
static member Format : IFormatProvider * System.Text.CompositeFormat * 'TArg0 * 'TArg1 -> string
Public Shared Function Format(Of TArg0, TArg1) (provider As IFormatProvider, format As CompositeFormat, arg0 As TArg0, arg1 As TArg1) As String

类型参数

TArg0

要设置格式的第一个对象的类型。

TArg1

要设置格式的第二个对象的类型。

参数

provider
IFormatProvider

一个提供区域性特定的格式设置信息的对象。

format
CompositeFormat

一个 CompositeFormat

arg0
TArg0

要设置格式的第一个对象。

arg1
TArg1

要设置格式的第二个对象。

返回

格式化的字符串。

例外

formatnull

格式项的索引大于或等于提供的参数数。

适用于

Format<TArg0>(IFormatProvider, CompositeFormat, TArg0)

将 中的 CompositeFormat 格式项替换为指定格式的相应对象的字符串表示形式。

public:
generic <typename TArg0>
 static System::String ^ Format(IFormatProvider ^ provider, System::Text::CompositeFormat ^ format, TArg0 arg0);
public static string Format<TArg0> (IFormatProvider? provider, System.Text.CompositeFormat format, TArg0 arg0);
static member Format : IFormatProvider * System.Text.CompositeFormat * 'TArg0 -> string
Public Shared Function Format(Of TArg0) (provider As IFormatProvider, format As CompositeFormat, arg0 As TArg0) As String

类型参数

TArg0

要设置格式的第一个对象的类型。

参数

provider
IFormatProvider

一个提供区域性特定的格式设置信息的对象。

format
CompositeFormat

一个 CompositeFormat

arg0
TArg0

要设置格式的第一个对象。

返回

格式化的字符串。

例外

formatnull

格式项的索引大于或等于提供的参数数。

适用于