StringBuilder.AppendFormat Metodo
Definizione
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di un argomento dell'oggetto corrispondente.Each format item is replaced by the string representation of a corresponding object argument.
Overload
AppendFormat(IFormatProvider, String, Object, Object, Object) |
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di uno di tre argomenti usando un provider del formato specificato.Each format item is replaced by the string representation of either of three arguments using a specified format provider. |
AppendFormat(String, Object) |
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di un singolo argomento.Each format item is replaced by the string representation of a single argument. |
AppendFormat(String, Object[]) |
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di un argomento corrispondente in una matrice di parametri.Each format item is replaced by the string representation of a corresponding argument in a parameter array. |
AppendFormat(IFormatProvider, String, Object) |
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di un singolo argomento usando un provider del formato specificato.Each format item is replaced by the string representation of a single argument using a specified format provider. |
AppendFormat(IFormatProvider, String, Object[]) |
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di un argomento corrispondente in una matrice di parametri usando un provider del formato specificato.Each format item is replaced by the string representation of a corresponding argument in a parameter array using a specified format provider. |
AppendFormat(String, Object, Object) |
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di uno dei due argomenti.Each format item is replaced by the string representation of either of two arguments. |
AppendFormat(IFormatProvider, String, Object, Object) |
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di uno di due argomenti usando un provider del formato specificato.Each format item is replaced by the string representation of either of two arguments using a specified format provider. |
AppendFormat(String, Object, Object, Object) |
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di uno dei tre argomenti.Each format item is replaced by the string representation of either of three arguments. |
AppendFormat(IFormatProvider, String, Object, Object, Object)
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di uno di tre argomenti usando un provider del formato specificato.Each format item is replaced by the string representation of either of three arguments using a specified format provider.
public:
System::Text::StringBuilder ^ AppendFormat(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2);
public System.Text.StringBuilder AppendFormat (IFormatProvider provider, string format, object arg0, object arg1, object arg2);
public System.Text.StringBuilder? AppendFormat (IFormatProvider provider, string? format, object arg0, object arg1, object arg2);
member this.AppendFormat : IFormatProvider * string * obj * obj * obj -> System.Text.StringBuilder
Public Function AppendFormat (provider As IFormatProvider, format As String, arg0 As Object, arg1 As Object, arg2 As Object) As StringBuilder
Parametri
- provider
- IFormatProvider
Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.An object that supplies culture-specific formatting information.
- format
- String
Stringa in formato composito.A composite format string.
- arg0
- Object
Primo oggetto da formattare.The first object to format.
- arg1
- Object
Secondo oggetto da formattare.The second object to format.
- arg2
- Object
Terzo oggetto da formattare.The third object to format.
Restituisce
Riferimento a questa istanza dopo il completamento dell'operazione di accodamento.A reference to this instance after the append operation has completed. Al termine dell'operazione di accodamento, questa istanza conterrà tutti i dati esistenti prima dell'operazione, seguiti da una copia di format
in cui le specifiche di formato vengono sostituite dalla rappresentazione di stringa dell'argomento dell'oggetto corrispondente.After the append operation, this instance contains any data that existed before the operation, suffixed by a copy of format
where any format specification is replaced by the string representation of the corresponding object argument.
Eccezioni
format
è null
.format
is null
.
format
non è valido.format
is invalid.
-oppure--or-
L'indice di un elemento di formato è minore di 0 (zero) oppure maggiore o uguale a 3 (tre).The index of a format item is less than 0 (zero), or greater than or equal to 3 (three).
La lunghezza della stringa espansa supererebbe MaxCapacity.The length of the expanded string would exceed MaxCapacity.
Esempio
Nell'esempio seguente viene usato il AppendFormat(IFormatProvider, String, Object, Object, Object) metodo per illustrare il risultato di un' And
operazione booleana con valori integer.The following example uses the AppendFormat(IFormatProvider, String, Object, Object, Object) method to illustrate the result of a Boolean And
operation with integer values. Si noti che la stringa di formato include sei elementi di formato, ma il metodo ha solo tre elementi nell'elenco di argomenti, perché ogni elemento è formattato in due modi diversi.Note that the format string includes six format items, but the method has only three items in its argument list, because each item is formatted in two different ways.
using System;
using System.Globalization;
using System.Text;
public class Example
{
public static void Main()
{
Random rnd = new Random();
CultureInfo culture = CultureInfo.CreateSpecificCulture("fr-FR");
StringBuilder sb = new StringBuilder();
string formatString = " {0,12:N0} ({0,8:X8})\n" +
"And {1,12:N0} ({1,8:X8})\n" +
" = {2,12:N0} ({2,8:X8})\n";
for (int ctr = 0; ctr <= 2; ctr++) {
int value1 = rnd.Next();
int value2 = rnd.Next();
sb.AppendFormat(culture, formatString,
value1, value2, value1 & value2).
AppendLine();
}
Console.WriteLine(sb.ToString());
}
}
// The example displays output like the following:
// 1 984 112 195 (76432643)
// And 1 179 778 511 (4651FDCF)
// = 1 178 674 243 (46412443)
//
// 2 034 813 710 (7948CB0E)
// And 569 333 976 (21EF58D8)
// = 558 385 160 (21484808)
//
// 126 717 735 (078D8F27)
// And 1 830 715 973 (6D1E8245)
// = 84 705 797 (050C8205)
Imports System.Globalization
Imports System.Text
Public Module Example
Public Sub Main()
Dim rnd As New Random()
Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture("fr-FR")
Dim sb As New StringBuilder()
Dim formatString As String = " {0,12:N0} ({0,8:X8})" + vbCrLf +
"And {1,12:N0} ({1,8:X8})" + vbCrLf +
" = {2,12:N0} ({2,8:X8})" + vbCrLf
For ctr As Integer = 0 To 2
Dim value1 As Integer = rnd.Next()
Dim value2 As Integer = rnd.Next()
sb.AppendFormat(culture, formatString,
value1, value2, value1 And value2).AppendLine()
Next
Console.WriteLine(sb.ToString())
End Sub
End Module
' The example displays the following output:
' 1 984 112 195 (76432643)
' And 1 179 778 511 (4651FDCF)
' = 1 178 674 243 (46412443)
'
' 2 034 813 710 (7948CB0E)
' And 569 333 976 (21EF58D8)
' = 558 385 160 (21484808)
'
' 126 717 735 (078D8F27)
' And 1 830 715 973 (6D1E8245)
' = 84 705 797 (050C8205)
Commenti
Questo metodo utilizza la funzionalità di formattazione composita del .NET Framework per convertire il valore di un oggetto nella relativa rappresentazione testuale e incorporare tale rappresentazione nell' StringBuilder oggetto corrente.This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in the current StringBuilder object.
Il format
parametro è costituito da zero o più esecuzioni di testo combinate con zero o più segnaposto indicizzati, denominati elementi di formato, che corrispondono a oggetti nell'elenco di parametri di questo metodo.The format
parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to objects in the parameter list of this method. Il processo di formattazione sostituisce ogni elemento di formato con la rappresentazione di stringa dell'oggetto corrispondente.The formatting process replaces each format item with the string representation of the corresponding object.
La sintassi di un elemento di formato è la seguente:The syntax of a format item is as follows:
{index[,length] [:FormatString]}{index[,length][:formatString]}
Gli elementi tra parentesi quadre sono facoltativi.Elements in square brackets are optional. La tabella seguente descrive i singoli elementi.The following table describes each element.
ElementoElement | DescrizioneDescription |
---|---|
indexindex | Posizione in base zero nell'elenco di parametri dell'oggetto da formattare.The zero-based position in the parameter list of the object to be formatted. Se l'oggetto specificato da index è null , l'elemento di formato viene sostituito da String.Empty .If the object specified by index is null , the format item is replaced by String.Empty. Se non è presente alcun parametro nella posizione dell' Indice , FormatException viene generata un'eccezione.If there is no parameter in the index position, a FormatException is thrown. |
,lunghezza,length | Numero minimo di caratteri nella rappresentazione di stringa del parametro.The minimum number of characters in the string representation of the parameter. Se positivo, il parametro è allineato a destra; Se negativo, è allineato a sinistra.If positive, the parameter is right-aligned; if negative, it is left-aligned. |
:FormatString:formatString | Stringa di formato standard o personalizzata supportata dal parametro.A standard or custom format string that is supported by the parameter. |
Nota
Per le stringhe di formato standard e personalizzate usate con i valori di data e ora, vedere stringhe di formato di data e ora standard e stringhe di formato di data e ora personalizzate.For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. Per le stringhe di formato standard e personalizzate usate con i valori numerici, vedere stringhe di formato numerico standard e stringhe di formato numerico personalizzate.For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. Per le stringhe di formato standard usate con le enumerazioni, vedere stringhe di formato di enumerazione.For the standard format strings used with enumerations, see Enumeration Format Strings.
Il provider
parametro specifica un' IFormatProvider implementazione di che può fornire informazioni sulla formattazione per arg0
e arg1
.The provider
parameter specifies an IFormatProvider implementation that can provide formatting information for arg0
and arg1
. provider
può essere uno degli elementi seguenti:provider
can be any of the following:
CultureInfoOggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.A CultureInfo object that provides culture-specific formatting information.
NumberFormatInfoOggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura per
arg0
oarg1
se sono valori numerici.A NumberFormatInfo object that provides culture-specific formatting information forarg0
orarg1
if they are numeric values.DateTimeFormatInfoOggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura per
arg0
,arg1
oarg2
se sono valori di data e ora.A DateTimeFormatInfo object that provides culture-specific formatting information forarg0
,arg1
, orarg2
if they are date and time values.Implementazione personalizzata IFormatProvider che fornisce informazioni sulla formattazione per
arg0
,arg1
earg2
.A custom IFormatProvider implementation that provides formatting information forarg0
,arg1
, andarg2
. In genere, tale implementazione implementa anche l' ICustomFormatter interfaccia.Typically, such an implementation also implements the ICustomFormatter interface.
Se il provider
parametro è null
, le informazioni sul provider di formato vengono ottenute dalle impostazioni cultura correnti.If the provider
parameter is null
, format provider information is obtained from the current culture.
arg0
, arg1
e arg2
rappresentano gli oggetti da formattare.arg0
, arg1
, and arg2
represent the objects to be formatted. Ogni elemento di formato in format
viene sostituito con la rappresentazione di stringa dell'oggetto con l'indice corrispondente.Each format item in format
is replaced with the string representation of the object that has the corresponding index. Se l'elemento di formato include formatString
e l'argomento corrispondente implementa l' IFormattable interfaccia, il metodo dell'argomento ToString(formatString, provider)
definisce la formattazione.If the format item includes formatString
and the corresponding argument implements the IFormattable interface, then the argument's ToString(formatString, provider)
method defines the formatting. In caso contrario, il ToString()
metodo dell'argomento definisce la formattazione.Otherwise, the argument's ToString()
method defines the formatting.
Note per i chiamanti
In .NET Core e in .NET Framework 4,0 e versioni successive, quando si crea un'istanza dell' StringBuilder oggetto chiamando il StringBuilder(Int32, Int32) costruttore, sia la lunghezza che la capacità dell' StringBuilder istanza possono superare il valore della MaxCapacity Proprietà.In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. Questa situazione può verificarsi in particolare quando si chiamano i Append(String) AppendFormat(String, Object) metodi e per aggiungere stringhe di piccole dimensioni.This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.
Vedi anche
- Formattazione di tipi in .NETFormatting Types in .NET
- Formattazione compositaComposite Formatting
- Procedura: Definire e usare provider di formati numerici personalizzatiHow to: Define and Use Custom Numeric Format Providers
- Stringhe di formato numerico standardStandard Numeric Format Strings
- Stringhe di formato numerico personalizzatoCustom Numeric Format Strings
- Stringhe di formato di data e ora standardStandard Date and Time Format Strings
- Stringhe di formato di data e ora personalizzatoCustom Date and Time Format Strings
- Stringhe di formato TimeSpan standardStandard TimeSpan Format Strings
- Stringhe di formato TimeSpan personalizzateCustom TimeSpan Format Strings
- Stringhe di formato di enumerazioneEnumeration Format Strings
Si applica a
AppendFormat(String, Object)
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di un singolo argomento.Each format item is replaced by the string representation of a single argument.
public:
System::Text::StringBuilder ^ AppendFormat(System::String ^ format, System::Object ^ arg0);
public System.Text.StringBuilder AppendFormat (string format, object arg0);
public System.Text.StringBuilder AppendFormat (string format, object? arg0);
member this.AppendFormat : string * obj -> System.Text.StringBuilder
Public Function AppendFormat (format As String, arg0 As Object) As StringBuilder
Parametri
- format
- String
Stringa in formato composito.A composite format string.
- arg0
- Object
Oggetto da formattare.An object to format.
Restituisce
Riferimento a questa istanza con format
accodato.A reference to this instance with format
appended. Ogni elemento di formato in format
viene sostituito dalla rappresentazione di stringa di arg0
.Each format item in format
is replaced by the string representation of arg0
.
Eccezioni
format
è null
.format
is null
.
format
non è valido.format
is invalid.
-oppure--or-
L'indice di un elemento di formato è minore di 0 (zero) oppure maggiore o uguale a 1 (uno).The index of a format item is less than 0 (zero), or greater than or equal to 1.
La lunghezza della stringa espansa supererebbe MaxCapacity.The length of the expanded string would exceed MaxCapacity.
Esempio
Nell'esempio seguente viene illustrato il AppendFormat metodo.The following example demonstrates the AppendFormat method.
using namespace System;
using namespace System::Text;
using namespace System::Globalization;
void Show( StringBuilder^ sbs )
{
Console::WriteLine( sbs );
sbs->Length = 0;
}
int main()
{
StringBuilder^ sb = gcnew StringBuilder;
int var1 = 111;
float var2 = 2.22F;
String^ var3 = "abcd";
array<Object^>^var4 = {3,4.4,(Char)'X'};
Console::WriteLine();
Console::WriteLine( "StringBuilder.AppendFormat method:" );
sb->AppendFormat( "1) {0}", var1 );
Show( sb );
sb->AppendFormat( "2) {0}, {1}", var1, var2 );
Show( sb );
sb->AppendFormat( "3) {0}, {1}, {2}", var1, var2, var3 );
Show( sb );
sb->AppendFormat( "4) {0}, {1}, {2}", var4 );
Show( sb );
CultureInfo^ ci = gcnew CultureInfo( "es-ES",true );
array<Object^>^temp1 = {var2};
sb->AppendFormat( ci, "5) {0}", temp1 );
Show( sb );
}
/*
This example produces the following results:
StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
using System;
using System.Text;
using System.Globalization;
class Sample
{
static StringBuilder sb = new StringBuilder();
public static void Main()
{
int var1 = 111;
float var2 = 2.22F;
string var3 = "abcd";
object[] var4 = {3, 4.4, 'X'};
Console.WriteLine();
Console.WriteLine("StringBuilder.AppendFormat method:");
sb.AppendFormat("1) {0}", var1);
Show(sb);
sb.AppendFormat("2) {0}, {1}", var1, var2);
Show(sb);
sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3);
Show(sb);
sb.AppendFormat("4) {0}, {1}, {2}", var4);
Show(sb);
CultureInfo ci = new CultureInfo("es-ES", true);
sb.AppendFormat(ci, "5) {0}", var2);
Show(sb);
}
public static void Show(StringBuilder sbs)
{
Console.WriteLine(sbs.ToString());
sb.Length = 0;
}
}
/*
This example produces the following results:
StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
Imports System.Text
Imports System.Globalization
Class Sample
Private Shared sb As New StringBuilder()
Public Shared Sub Main()
Dim var1 As Integer = 111
Dim var2 As Single = 2.22F
Dim var3 As String = "abcd"
Dim var4 As Object() = {3, 4.4, "X"c}
Console.WriteLine()
Console.WriteLine("StringBuilder.AppendFormat method:")
sb.AppendFormat("1) {0}", var1)
Show(sb)
sb.AppendFormat("2) {0}, {1}", var1, var2)
Show(sb)
sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3)
Show(sb)
sb.AppendFormat("4) {0}, {1}, {2}", var4)
Show(sb)
Dim ci As New CultureInfo("es-ES", True)
sb.AppendFormat(ci, "5) {0}", var2)
Show(sb)
End Sub
Public Shared Sub Show(sbs As StringBuilder)
Console.WriteLine(sbs.ToString())
sb.Length = 0
End Sub
End Class
'
'This example produces the following results:
'
'StringBuilder.AppendFormat method:
'1) 111
'2) 111, 2.22
'3) 111, 2.22, abcd
'4) 3, 4.4, X
'5) 2,22
Commenti
Questo metodo utilizza la funzionalità di formattazione composita del .NET Framework per convertire il valore di un oggetto nella relativa rappresentazione testuale e incorporare tale rappresentazione nell' StringBuilder oggetto corrente.This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in the current StringBuilder object.
Il format
parametro è costituito da zero o più esecuzioni di testo combinate con zero o più segnaposto indicizzati, denominati elementi di formato.The format
parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items. L'indice degli elementi di formato deve essere 0, in modo che corrisponda a arg0
, il singolo oggetto nell'elenco di parametri di questo metodo.The index of the format items must be 0, to correspond to arg0
, the single object in the parameter list of this method. Il processo di formattazione sostituisce ogni elemento di formato con la rappresentazione di stringa di arg0
.The formatting process replaces each format item with the string representation of arg0
.
La sintassi di un elemento di formato è la seguente:The syntax of a format item is as follows:
{index[,length] [:FormatString]}{index[,length][:formatString]}
Gli elementi tra parentesi quadre sono facoltativi.Elements in square brackets are optional. La tabella seguente descrive i singoli elementi.The following table describes each element.
ElementoElement | DescrizioneDescription |
---|---|
indexindex | Posizione in base zero nell'elenco di parametri dell'oggetto da formattare.The zero-based position in the parameter list of the object to be formatted. Se l'oggetto specificato da index è null , l'elemento di formato viene sostituito da String.Empty .If the object specified by index is null , the format item is replaced by String.Empty. Se non è presente alcun parametro nella posizione dell' Indice , FormatException viene generata un'eccezione.If there is no parameter in the index position, a FormatException is thrown. |
,lunghezza,length | Numero minimo di caratteri nella rappresentazione di stringa del parametro.The minimum number of characters in the string representation of the parameter. Se positivo, il parametro è allineato a destra; Se negativo, è allineato a sinistra.If positive, the parameter is right-aligned; if negative, it is left-aligned. |
:FormatString:formatString | Stringa di formato standard o personalizzata supportata dal parametro.A standard or custom format string that is supported by the parameter. |
Nota
Per le stringhe di formato standard e personalizzate usate con i valori di data e ora, vedere stringhe di formato di data e ora standard e stringhe di formato di data e ora personalizzate.For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. Per le stringhe di formato standard e personalizzate usate con i valori numerici, vedere stringhe di formato numerico standard e stringhe di formato numerico personalizzate.For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. Per le stringhe di formato standard usate con le enumerazioni, vedere stringhe di formato di enumerazione.For the standard format strings used with enumerations, see Enumeration Format Strings.
arg0
rappresenta l'oggetto da formattare.arg0
represents the object to be formatted. Ogni elemento di formato in format
viene sostituito con la rappresentazione di stringa di arg0
.Each format item in format
is replaced with the string representation of arg0
. Se l'elemento di formato include formatString
e arg0
implementa l' IFormattable interfaccia, arg0.ToString(formatString, null)
definisce la formattazione.If the format item includes formatString
and arg0
implements the IFormattable interface, then arg0.ToString(formatString, null)
defines the formatting. In caso contrario, arg0.ToString()
definisce la formattazione.Otherwise, arg0.ToString()
defines the formatting.
Se la stringa assegnata a format
è "Grazie per la donazione di {0: # # # #} lattine di cibo per la nostra organizzazione caritatevole".If the string assigned to format
is "Thank you for your donation of {0:####} cans of food to our charitable organization." e arg0
è un numero intero con valore 10, il valore restituito sarà "Grazie per la donazione di 10 lattine di cibo alla nostra organizzazione caritatevole".and arg0
is an integer with the value 10, the return value will be "Thank you for your donation of 10 cans of food to our charitable organization."
Note per i chiamanti
In .NET Core e in .NET Framework 4,0 e versioni successive, quando si crea un'istanza dell' StringBuilder oggetto chiamando il StringBuilder(Int32, Int32) costruttore, sia la lunghezza che la capacità dell' StringBuilder istanza possono superare il valore della MaxCapacity Proprietà.In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. Questa situazione può verificarsi in particolare quando si chiamano i Append(String) AppendFormat(String, Object) metodi e per aggiungere stringhe di piccole dimensioni.This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.
Vedi anche
- Formattazione di tipi in .NETFormatting Types in .NET
- Formattazione compositaComposite Formatting
- Stringhe di formato numerico standardStandard Numeric Format Strings
- Stringhe di formato numerico personalizzatoCustom Numeric Format Strings
- Stringhe di formato di data e ora standardStandard Date and Time Format Strings
- Stringhe di formato di data e ora personalizzatoCustom Date and Time Format Strings
- Stringhe di formato TimeSpan standardStandard TimeSpan Format Strings
- Stringhe di formato TimeSpan personalizzateCustom TimeSpan Format Strings
- Stringhe di formato di enumerazioneEnumeration Format Strings
Si applica a
AppendFormat(String, Object[])
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di un argomento corrispondente in una matrice di parametri.Each format item is replaced by the string representation of a corresponding argument in a parameter array.
public:
System::Text::StringBuilder ^ AppendFormat(System::String ^ format, ... cli::array <System::Object ^> ^ args);
public System.Text.StringBuilder AppendFormat (string format, params object[] args);
public System.Text.StringBuilder AppendFormat (string format, params object[]? args);
member this.AppendFormat : string * obj[] -> System.Text.StringBuilder
Public Function AppendFormat (format As String, ParamArray args As Object()) As StringBuilder
Parametri
- format
- String
Stringa in formato composito.A composite format string.
- args
- Object[]
Matrice di oggetti da formattare.An array of objects to format.
Restituisce
Riferimento a questa istanza con format
accodato.A reference to this instance with format
appended. Ogni elemento di formato in format
viene sostituito dalla rappresentazione di stringa dell'argomento dell'oggetto corrispondente.Each format item in format
is replaced by the string representation of the corresponding object argument.
Eccezioni
format
o args
è null
.format
or args
is null
.
format
non è valido.format
is invalid.
-oppure--or-
L'indice di un elemento di formato è minore di zero oppure maggiore o uguale alla lunghezza della matrice args
.The index of a format item is less than 0 (zero), or greater than or equal to the length of the args
array.
La lunghezza della stringa espansa supererebbe MaxCapacity.The length of the expanded string would exceed MaxCapacity.
Esempio
Nell'esempio seguente viene illustrato il AppendFormat metodo.The following example demonstrates the AppendFormat method.
using namespace System;
using namespace System::Text;
using namespace System::Globalization;
void Show( StringBuilder^ sbs )
{
Console::WriteLine( sbs );
sbs->Length = 0;
}
int main()
{
StringBuilder^ sb = gcnew StringBuilder;
int var1 = 111;
float var2 = 2.22F;
String^ var3 = "abcd";
array<Object^>^var4 = {3,4.4,(Char)'X'};
Console::WriteLine();
Console::WriteLine( "StringBuilder.AppendFormat method:" );
sb->AppendFormat( "1) {0}", var1 );
Show( sb );
sb->AppendFormat( "2) {0}, {1}", var1, var2 );
Show( sb );
sb->AppendFormat( "3) {0}, {1}, {2}", var1, var2, var3 );
Show( sb );
sb->AppendFormat( "4) {0}, {1}, {2}", var4 );
Show( sb );
CultureInfo^ ci = gcnew CultureInfo( "es-ES",true );
array<Object^>^temp1 = {var2};
sb->AppendFormat( ci, "5) {0}", temp1 );
Show( sb );
}
/*
This example produces the following results:
StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
using System;
using System.Text;
using System.Globalization;
class Sample
{
static StringBuilder sb = new StringBuilder();
public static void Main()
{
int var1 = 111;
float var2 = 2.22F;
string var3 = "abcd";
object[] var4 = {3, 4.4, 'X'};
Console.WriteLine();
Console.WriteLine("StringBuilder.AppendFormat method:");
sb.AppendFormat("1) {0}", var1);
Show(sb);
sb.AppendFormat("2) {0}, {1}", var1, var2);
Show(sb);
sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3);
Show(sb);
sb.AppendFormat("4) {0}, {1}, {2}", var4);
Show(sb);
CultureInfo ci = new CultureInfo("es-ES", true);
sb.AppendFormat(ci, "5) {0}", var2);
Show(sb);
}
public static void Show(StringBuilder sbs)
{
Console.WriteLine(sbs.ToString());
sb.Length = 0;
}
}
/*
This example produces the following results:
StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
Imports System.Text
Imports System.Globalization
Class Sample
Private Shared sb As New StringBuilder()
Public Shared Sub Main()
Dim var1 As Integer = 111
Dim var2 As Single = 2.22F
Dim var3 As String = "abcd"
Dim var4 As Object() = {3, 4.4, "X"c}
Console.WriteLine()
Console.WriteLine("StringBuilder.AppendFormat method:")
sb.AppendFormat("1) {0}", var1)
Show(sb)
sb.AppendFormat("2) {0}, {1}", var1, var2)
Show(sb)
sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3)
Show(sb)
sb.AppendFormat("4) {0}, {1}, {2}", var4)
Show(sb)
Dim ci As New CultureInfo("es-ES", True)
sb.AppendFormat(ci, "5) {0}", var2)
Show(sb)
End Sub
Public Shared Sub Show(sbs As StringBuilder)
Console.WriteLine(sbs.ToString())
sb.Length = 0
End Sub
End Class
'
'This example produces the following results:
'
'StringBuilder.AppendFormat method:
'1) 111
'2) 111, 2.22
'3) 111, 2.22, abcd
'4) 3, 4.4, X
'5) 2,22
Commenti
Questo metodo utilizza la funzionalità di formattazione composita del .NET Framework per convertire il valore di un oggetto nella relativa rappresentazione testuale e incorporare tale rappresentazione nell' StringBuilder oggetto corrente.This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in the current StringBuilder object.
Il format
parametro è costituito da zero o più esecuzioni di testo combinate con zero o più segnaposto indicizzati, denominati elementi di formato, che corrispondono a oggetti nell'elenco di parametri di questo metodo.The format
parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to objects in the parameter list of this method. Il processo di formattazione sostituisce ogni elemento di formato con la rappresentazione di stringa dell'oggetto corrispondente.The formatting process replaces each format item with the string representation of the corresponding object.
La sintassi di un elemento di formato è la seguente:The syntax of a format item is as follows:
{index[,length] [:FormatString]}{index[,length][:formatString]}
Gli elementi tra parentesi quadre sono facoltativi.Elements in square brackets are optional. La tabella seguente descrive i singoli elementi.The following table describes each element.
ElementoElement | DescrizioneDescription |
---|---|
indexindex | Posizione in base zero nell'elenco di parametri dell'oggetto da formattare.The zero-based position in the parameter list of the object to be formatted. Se l'oggetto specificato da index è null , l'elemento di formato viene sostituito da String.Empty .If the object specified by index is null , the format item is replaced by String.Empty. Se non è presente alcun parametro nella posizione dell' Indice , FormatException viene generata un'eccezione.If there is no parameter in the index position, a FormatException is thrown. |
,lunghezza,length | Numero minimo di caratteri nella rappresentazione di stringa del parametro.The minimum number of characters in the string representation of the parameter. Se positivo, il parametro è allineato a destra; Se negativo, è allineato a sinistra.If positive, the parameter is right-aligned; if negative, it is left-aligned. |
:FormatString:formatString | Stringa di formato standard o personalizzata supportata dal parametro.A standard or custom format string that is supported by the parameter. |
Nota
Per le stringhe di formato standard e personalizzate usate con i valori di data e ora, vedere stringhe di formato di data e ora standard e stringhe di formato di data e ora personalizzate.For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. Per le stringhe di formato standard e personalizzate usate con i valori numerici, vedere stringhe di formato numerico standard e stringhe di formato numerico personalizzate.For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. Per le stringhe di formato standard usate con le enumerazioni, vedere stringhe di formato di enumerazione.For the standard format strings used with enumerations, see Enumeration Format Strings.
args
rappresenta gli oggetti da formattare.args
represents the objects to be formatted. Ogni elemento di formato in format
viene sostituito con la rappresentazione di stringa dell'oggetto corrispondente in args
.Each format item in format
is replaced with the string representation of the corresponding object in args
. Se l'elemento di formato include formatString
e l'oggetto corrispondente in args
implementa l' IFormattable interfaccia, args[index].ToString(formatString, provider)
definisce la formattazione.If the format item includes formatString
and the corresponding object in args
implements the IFormattable interface, then args[index].ToString(formatString, provider)
defines the formatting. In caso contrario, args[index].ToString()
definisce la formattazione.Otherwise, args[index].ToString()
defines the formatting.
Se la stringa assegnata a format
è "Grazie per la donazione di {0: # # # #} lattine di cibo per la nostra organizzazione caritatevole".If the string assigned to format
is "Thank you for your donation of {0:####} cans of food to our charitable organization." e arg0
è un numero intero con valore 10, il valore restituito sarà "Grazie per la donazione di 10 lattine di cibo alla nostra organizzazione caritatevole".and arg0
is an integer with the value 10, the return value will be "Thank you for your donation of 10 cans of food to our charitable organization."
Note per i chiamanti
In .NET Core e in .NET Framework 4,0 e versioni successive, quando si crea un'istanza dell' StringBuilder oggetto chiamando il StringBuilder(Int32, Int32) costruttore, sia la lunghezza che la capacità dell' StringBuilder istanza possono superare il valore della MaxCapacity Proprietà.In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. Questa situazione può verificarsi in particolare quando si chiamano i Append(String) AppendFormat(String, Object) metodi e per aggiungere stringhe di piccole dimensioni.This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.
Vedi anche
- Formattazione di tipi in .NETFormatting Types in .NET
- Formattazione compositaComposite Formatting
- Stringhe di formato numerico standardStandard Numeric Format Strings
- Stringhe di formato numerico personalizzatoCustom Numeric Format Strings
- Stringhe di formato di data e ora standardStandard Date and Time Format Strings
- Stringhe di formato di data e ora personalizzatoCustom Date and Time Format Strings
- Stringhe di formato TimeSpan standardStandard TimeSpan Format Strings
- Stringhe di formato TimeSpan personalizzateCustom TimeSpan Format Strings
- Stringhe di formato di enumerazioneEnumeration Format Strings
Si applica a
AppendFormat(IFormatProvider, String, Object)
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di un singolo argomento usando un provider del formato specificato.Each format item is replaced by the string representation of a single argument using a specified format provider.
public:
System::Text::StringBuilder ^ AppendFormat(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0);
public System.Text.StringBuilder AppendFormat (IFormatProvider provider, string format, object arg0);
public System.Text.StringBuilder AppendFormat (IFormatProvider? provider, string format, object? arg0);
member this.AppendFormat : IFormatProvider * string * obj -> System.Text.StringBuilder
Public Function AppendFormat (provider As IFormatProvider, format As String, arg0 As Object) As StringBuilder
Parametri
- provider
- IFormatProvider
Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.An object that supplies culture-specific formatting information.
- format
- String
Stringa in formato composito.A composite format string.
- arg0
- Object
Oggetto da formattare.The object to format.
Restituisce
Riferimento a questa istanza dopo il completamento dell'operazione di accodamento.A reference to this instance after the append operation has completed. Al termine dell'operazione di accodamento, questa istanza conterrà tutti i dati esistenti prima dell'operazione, seguiti da una copia di format
in cui le specifiche di formato vengono sostituite dalla rappresentazione di stringa di arg0
.After the append operation, this instance contains any data that existed before the operation, suffixed by a copy of format
in which any format specification is replaced by the string representation of arg0
.
Eccezioni
format
è null
.format
is null
.
format
non è valido.format
is invalid.
-oppure--or-
L'indice di un elemento di formato è minore di 0 (zero) oppure maggiore o uguale a 1 (uno).The index of a format item is less than 0 (zero), or greater than or equal to one (1).
La lunghezza della stringa espansa supererebbe MaxCapacity.The length of the expanded string would exceed MaxCapacity.
Esempio
Di seguito sono incluse due chiamate al AppendFormat(IFormatProvider, String, Object) metodo.The following includes two calls to the AppendFormat(IFormatProvider, String, Object) method. Entrambi utilizzano le convenzioni di formattazione delle impostazioni cultura English-Great Bretagna (en-GB).Both use the formatting conventions of the English-Great Britain (en-GB) culture. Il primo inserisce la rappresentazione di stringa di una Decimal valuta del valore in una stringa di risultato.The first inserts the string representation of a Decimal value currency in a result string. Il secondo inserisce un DateTime valore in due posizioni in una stringa di risultato, il primo include solo la stringa di data breve e la seconda la stringa dell'ora breve.The second inserts a DateTime value in two places in a result string, the first including only the short date string and the second the short time string.
using System;
using System.Globalization;
using System.Text;
public class Example
{
public static void Main()
{
StringBuilder sb = new StringBuilder();
Decimal value = 16.95m;
CultureInfo enGB = CultureInfo.CreateSpecificCulture("en-GB");
DateTime dateToday = DateTime.Now;
sb.AppendFormat(enGB, "Final Price: {0:C2}", value);
sb.AppendLine();
sb.AppendFormat(enGB, "Date and Time: {0:d} at {0:t}", dateToday);
Console.WriteLine(sb.ToString());
}
}
// The example displays the following output:
// Final Price: £16.95
// Date and Time: 01/10/2014 at 10:22
Imports System.Globalization
Imports System.Text
Module Example
Public Sub Main()
Dim sb As New StringBuilder()
Dim value As Decimal = 16.95d
Dim enGB As CultureInfo = CultureInfo.CreateSpecificCulture("en-GB")
Dim dateToday As DateTime = Date.Now
sb.AppendFormat(enGB, "Final Price: {0:C2}", value)
sb.AppendLine()
sb.AppendFormat(enGB, "Date and Time: {0:d} at {0:t}", dateToday)
Console.WriteLine(sb.ToString())
End Sub
End Module
' The example displays output like the following:
' Final Price: £16.95
' Date and Time: 01/10/2014 at 10:22
Commenti
Questo metodo utilizza la funzionalità di formattazione composita del .NET Framework per convertire il valore di nella arg0
relativa rappresentazione testuale e incorporare tale rappresentazione nell' StringBuilder oggetto corrente.This method uses the composite formatting feature of the .NET Framework to convert the value of arg0
to its text representation and embed that representation in the current StringBuilder object.
Il format
parametro è costituito da zero o più esecuzioni di testo combinate con zero o più segnaposto indicizzati, denominati elementi di formato.The format
parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items. L'indice di ogni elemento di formato deve essere zero (0) poiché questo metodo include un elenco di argomenti con un solo argomento.The index of each format item must be zero (0) since this method includes an argument list with a single argument. Il processo di formattazione sostituisce ogni elemento di formato con la rappresentazione di stringa di arg0
.The formatting process replaces each format item with the string representation of arg0
.
La sintassi di un elemento di formato è la seguente:The syntax of a format item is as follows:
{index[,length] [:FormatString]}{index[,length][:formatString]}
Gli elementi tra parentesi quadre sono facoltativi.Elements in square brackets are optional. La tabella seguente descrive i singoli elementi.The following table describes each element.
ElementoElement | DescrizioneDescription |
---|---|
indexindex | Posizione in base zero nell'elenco di parametri dell'oggetto da formattare.The zero-based position in the parameter list of the object to be formatted. Se l'oggetto specificato da index è null , l'elemento di formato viene sostituito da String.Empty .If the object specified by index is null , the format item is replaced by String.Empty. In questo caso, poiché il AppendFormat(IFormatProvider, String, Object) metodo presenta un solo argomento nell'elenco di argomenti, il valore di index deve essere sempre 0.In this case, since the AppendFormat(IFormatProvider, String, Object) method has a single argument in the argument list, the value of index must always be 0. In caso contrario, FormatException viene generata un'eccezione.If it is not, a FormatException is thrown. |
,lunghezza,length | Numero minimo di caratteri nella rappresentazione di stringa del parametro.The minimum number of characters in the string representation of the parameter. Se positivo, il parametro è allineato a destra; Se negativo, è allineato a sinistra.If positive, the parameter is right-aligned; if negative, it is left-aligned. |
:FormatString:formatString | Stringa di formato standard o personalizzata supportata dal parametro.A standard or custom format string that is supported by the parameter. |
Nota
Per le stringhe di formato standard e personalizzate usate con i valori di data e ora, vedere stringhe di formato di data e ora standard e stringhe di formato di data e ora personalizzate.For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. Per le stringhe di formato standard e personalizzate usate con i valori numerici, vedere stringhe di formato numerico standard e stringhe di formato numerico personalizzate.For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. Per le stringhe di formato standard usate con le enumerazioni, vedere stringhe di formato di enumerazione.For the standard format strings used with enumerations, see Enumeration Format Strings.
Il provider
parametro specifica un' IFormatProvider implementazione di che può fornire informazioni sulla formattazione per gli oggetti in args
.The provider
parameter specifies an IFormatProvider implementation that can provide formatting information for the objects in args
. provider
può essere uno degli elementi seguenti:provider
can be any of the following:
CultureInfoOggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.A CultureInfo object that provides culture-specific formatting information.
NumberFormatInfoOggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura per
arg0
se è un valore numerico.A NumberFormatInfo object that provides culture-specific formatting information forarg0
if it is a numeric value.DateTimeFormatInfoOggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura per
arg0
se è un valore di data e ora.A DateTimeFormatInfo object that provides culture-specific formatting information forarg0
if it is a date and time value.Implementazione personalizzata di IFormatProvider che fornisce informazioni sulla formattazione per
arg0
.A custom IFormatProvider implementation that provides formatting information forarg0
. In genere, tale implementazione implementa anche l' ICustomFormatter interfaccia.Typically, such an implementation also implements the ICustomFormatter interface.
Se il provider
parametro è null
, le informazioni di formattazione vengono ottenute dalle impostazioni cultura correnti.If the provider
parameter is null
, formatting information is obtained from the current culture.
arg0
rappresenta l'oggetto da formattare.arg0
represents the object to be formatted. Ogni elemento di formato in format
viene sostituito con la rappresentazione di stringa di arg0
.Each format item in format
is replaced with the string representation of arg0
. Se l'elemento di formato include formatString
e arg0
implementa l' IFormattable interfaccia, arg0.ToString(formatString, provider)
definisce la formattazione.If the format item includes formatString
and arg0
implements the IFormattable interface, then arg0.ToString(formatString, provider)
defines the formatting. In caso contrario, arg0.ToString()
definisce la formattazione.Otherwise, arg0.ToString()
defines the formatting.
Note per i chiamanti
In .NET Core e in .NET Framework 4,0 e versioni successive, quando si crea un'istanza dell' StringBuilder oggetto chiamando il StringBuilder(Int32, Int32) costruttore, sia la lunghezza che la capacità dell' StringBuilder istanza possono superare il valore della MaxCapacity Proprietà.In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. Questa situazione può verificarsi in particolare quando si chiamano i Append(String) AppendFormat(String, Object) metodi e per aggiungere stringhe di piccole dimensioni.This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.
Vedi anche
- Formattazione di tipi in .NETFormatting Types in .NET
- Formattazione compositaComposite Formatting
- Procedura: Definire e usare provider di formati numerici personalizzatiHow to: Define and Use Custom Numeric Format Providers
- Stringhe di formato numerico standardStandard Numeric Format Strings
- Stringhe di formato numerico personalizzatoCustom Numeric Format Strings
- Stringhe di formato di data e ora standardStandard Date and Time Format Strings
- Stringhe di formato di data e ora personalizzatoCustom Date and Time Format Strings
- Stringhe di formato TimeSpan standardStandard TimeSpan Format Strings
- Stringhe di formato TimeSpan personalizzateCustom TimeSpan Format Strings
- Stringhe di formato di enumerazioneEnumeration Format Strings
Si applica a
AppendFormat(IFormatProvider, String, Object[])
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di un argomento corrispondente in una matrice di parametri usando un provider del formato specificato.Each format item is replaced by the string representation of a corresponding argument in a parameter array using a specified format provider.
public:
System::Text::StringBuilder ^ AppendFormat(IFormatProvider ^ provider, System::String ^ format, ... cli::array <System::Object ^> ^ args);
public System.Text.StringBuilder AppendFormat (IFormatProvider provider, string format, params object[] args);
public System.Text.StringBuilder AppendFormat (IFormatProvider? provider, string format, params object[]? args);
member this.AppendFormat : IFormatProvider * string * obj[] -> System.Text.StringBuilder
Public Function AppendFormat (provider As IFormatProvider, format As String, ParamArray args As Object()) As StringBuilder
Parametri
- provider
- IFormatProvider
Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.An object that supplies culture-specific formatting information.
- format
- String
Stringa in formato composito.A composite format string.
- args
- Object[]
Matrice di oggetti da formattare.An array of objects to format.
Restituisce
Riferimento a questa istanza dopo il completamento dell'operazione di accodamento.A reference to this instance after the append operation has completed. Al termine dell'operazione di accodamento, questa istanza conterrà tutti i dati esistenti prima dell'operazione, seguiti da una copia di format
in cui le specifiche di formato vengono sostituite dalla rappresentazione di stringa dell'argomento dell'oggetto corrispondente.After the append operation, this instance contains any data that existed before the operation, suffixed by a copy of format
where any format specification is replaced by the string representation of the corresponding object argument.
Eccezioni
format
è null
.format
is null
.
format
non è valido.format
is invalid.
-oppure--or-
L'indice di un elemento di formato è minore di zero oppure maggiore o uguale alla lunghezza della matrice args
.The index of a format item is less than 0 (zero), or greater than or equal to the length of the args
array.
La lunghezza della stringa espansa supererebbe MaxCapacity.The length of the expanded string would exceed MaxCapacity.
Esempio
Nell'esempio seguente viene illustrato il AppendFormat metodo.The following example demonstrates the AppendFormat method.
using namespace System;
using namespace System::Text;
using namespace System::Globalization;
void Show( StringBuilder^ sbs )
{
Console::WriteLine( sbs );
sbs->Length = 0;
}
int main()
{
StringBuilder^ sb = gcnew StringBuilder;
int var1 = 111;
float var2 = 2.22F;
String^ var3 = "abcd";
array<Object^>^var4 = {3,4.4,(Char)'X'};
Console::WriteLine();
Console::WriteLine( "StringBuilder.AppendFormat method:" );
sb->AppendFormat( "1) {0}", var1 );
Show( sb );
sb->AppendFormat( "2) {0}, {1}", var1, var2 );
Show( sb );
sb->AppendFormat( "3) {0}, {1}, {2}", var1, var2, var3 );
Show( sb );
sb->AppendFormat( "4) {0}, {1}, {2}", var4 );
Show( sb );
CultureInfo^ ci = gcnew CultureInfo( "es-ES",true );
array<Object^>^temp1 = {var2};
sb->AppendFormat( ci, "5) {0}", temp1 );
Show( sb );
}
/*
This example produces the following results:
StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
using System;
using System.Text;
using System.Globalization;
class Sample
{
static StringBuilder sb = new StringBuilder();
public static void Main()
{
int var1 = 111;
float var2 = 2.22F;
string var3 = "abcd";
object[] var4 = {3, 4.4, 'X'};
Console.WriteLine();
Console.WriteLine("StringBuilder.AppendFormat method:");
sb.AppendFormat("1) {0}", var1);
Show(sb);
sb.AppendFormat("2) {0}, {1}", var1, var2);
Show(sb);
sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3);
Show(sb);
sb.AppendFormat("4) {0}, {1}, {2}", var4);
Show(sb);
CultureInfo ci = new CultureInfo("es-ES", true);
sb.AppendFormat(ci, "5) {0}", var2);
Show(sb);
}
public static void Show(StringBuilder sbs)
{
Console.WriteLine(sbs.ToString());
sb.Length = 0;
}
}
/*
This example produces the following results:
StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
Imports System.Text
Imports System.Globalization
Class Sample
Private Shared sb As New StringBuilder()
Public Shared Sub Main()
Dim var1 As Integer = 111
Dim var2 As Single = 2.22F
Dim var3 As String = "abcd"
Dim var4 As Object() = {3, 4.4, "X"c}
Console.WriteLine()
Console.WriteLine("StringBuilder.AppendFormat method:")
sb.AppendFormat("1) {0}", var1)
Show(sb)
sb.AppendFormat("2) {0}, {1}", var1, var2)
Show(sb)
sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3)
Show(sb)
sb.AppendFormat("4) {0}, {1}, {2}", var4)
Show(sb)
Dim ci As New CultureInfo("es-ES", True)
sb.AppendFormat(ci, "5) {0}", var2)
Show(sb)
End Sub
Public Shared Sub Show(sbs As StringBuilder)
Console.WriteLine(sbs.ToString())
sb.Length = 0
End Sub
End Class
'
'This example produces the following results:
'
'StringBuilder.AppendFormat method:
'1) 111
'2) 111, 2.22
'3) 111, 2.22, abcd
'4) 3, 4.4, X
'5) 2,22
Nell'esempio seguente viene definita un' IFormatProvider implementazione personalizzata denominata CustomerFormatter
che formatta un numero di cliente a 10 cifre con trattini dopo la quarta e la settima cifra.The following example defines a custom IFormatProvider implementation named CustomerFormatter
that formats a 10-digit customer number with hyphens after the fourth and seventh digits. Viene passato al StringBuilder.AppendFormat(IFormatProvider, String, Object[]) metodo per creare una stringa che includa il numero di cliente formattato e il nome del cliente.It is passed to the StringBuilder.AppendFormat(IFormatProvider, String, Object[]) method to create a string that includes the formatted customer number and customer name.
using System;
using System.Text;
public class Customer
{
private string custName;
private int custNumber;
public Customer(string name, int number)
{
this.custName = name;
this.custNumber = number;
}
public string Name
{
get { return this.custName; }
}
public int CustomerNumber
{
get { return this.custNumber; }
}
}
public class CustomerNumberFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
return null;
}
public string Format(string format, object arg, IFormatProvider provider)
{
if (arg is Int32)
{
string custNumber = ((int) arg).ToString("D10");
return custNumber.Substring(0, 4) + "-" + custNumber.Substring(4, 3) +
"-" + custNumber.Substring(7, 3);
}
else
{
return null;
}
}
}
public class Example
{
public static void Main()
{
Customer customer = new Customer("A Plus Software", 903654);
StringBuilder sb = new StringBuilder();
sb.AppendFormat(new CustomerNumberFormatter(), "{0}: {1}",
customer.CustomerNumber, customer.Name);
Console.WriteLine(sb.ToString());
}
}
// The example displays the following output:
// 0000-903-654: A Plus Software
Imports System.Text
Public Class Customer
Private custName As String
Private custNumber As Integer
Public Sub New(name As String, number As Integer)
custName = name
custNumber = number
End Sub
Public ReadOnly Property Name As String
Get
Return Me.custName
End Get
End Property
Public ReadOnly Property CustomerNumber As Integer
Get
Return Me.custNumber
End Get
End Property
End Class
Public Class CustomerNumberFormatter
Implements IFormatProvider, ICustomFormatter
Public Function GetFormat(formatType As Type) As Object _
Implements IFormatProvider.GetFormat
If formatType Is GetType(ICustomFormatter) Then
Return Me
End If
Return Nothing
End Function
Public Function Format(fmt As String, arg As Object, provider As IFormatProvider) As String _
Implements ICustomFormatter.Format
If typeof arg Is Int32 Then
Dim custNumber As String = CInt(arg).ToString("D10")
Return custNumber.Substring(0, 4) + "-" + custNumber.SubString(4, 3) + _
"-" + custNumber.Substring(7, 3)
Else
Return Nothing
End If
End Function
End Class
Module Example
Public Sub Main()
Dim customer As New Customer("A Plus Software", 903654)
Dim sb As New StringBuilder()
sb.AppendFormat(New CustomerNumberFormatter, "{0}: {1}", _
customer.CustomerNumber, customer.Name)
Console.WriteLine(sb.ToString())
End Sub
End Module
' The example displays the following output:
' 0000-903-654: A Plus Software
Commenti
Questo metodo utilizza la funzionalità di formattazione composita del .NET Framework per convertire il valore di un oggetto nella relativa rappresentazione testuale e incorporare tale rappresentazione nell' StringBuilder oggetto corrente.This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in the current StringBuilder object.
Il format
parametro è costituito da zero o più esecuzioni di testo combinate con zero o più segnaposto indicizzati, denominati elementi di formato, che corrispondono a oggetti nell'elenco di parametri di questo metodo.The format
parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to objects in the parameter list of this method. Il processo di formattazione sostituisce ogni elemento di formato con la rappresentazione di stringa dell'oggetto corrispondente.The formatting process replaces each format item with the string representation of the corresponding object.
La sintassi di un elemento di formato è la seguente:The syntax of a format item is as follows:
{index[,length] [:FormatString]}{index[,length][:formatString]}
Gli elementi tra parentesi quadre sono facoltativi.Elements in square brackets are optional. La tabella seguente descrive i singoli elementi.The following table describes each element.
ElementoElement | DescrizioneDescription |
---|---|
indexindex | Posizione in base zero nell'elenco di parametri dell'oggetto da formattare.The zero-based position in the parameter list of the object to be formatted. Se l'oggetto specificato da index è null , l'elemento di formato viene sostituito da String.Empty .If the object specified by index is null , the format item is replaced by String.Empty. Se non è presente alcun parametro nella posizione dell' Indice , FormatException viene generata un'eccezione.If there is no parameter in the index position, a FormatException is thrown. |
,lunghezza,length | Numero minimo di caratteri nella rappresentazione di stringa del parametro.The minimum number of characters in the string representation of the parameter. Se positivo, il parametro è allineato a destra; Se negativo, è allineato a sinistra.If positive, the parameter is right-aligned; if negative, it is left-aligned. |
:FormatString:formatString | Stringa di formato standard o personalizzata supportata dal parametro.A standard or custom format string that is supported by the parameter. |
Nota
Per le stringhe di formato standard e personalizzate usate con i valori di data e ora, vedere stringhe di formato di data e ora standard e stringhe di formato di data e ora personalizzate.For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. Per le stringhe di formato standard e personalizzate usate con i valori numerici, vedere stringhe di formato numerico standard e stringhe di formato numerico personalizzate.For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. Per le stringhe di formato standard usate con le enumerazioni, vedere stringhe di formato di enumerazione.For the standard format strings used with enumerations, see Enumeration Format Strings.
Il provider
parametro specifica un' IFormatProvider implementazione di che può fornire informazioni sulla formattazione per gli oggetti in args
.The provider
parameter specifies an IFormatProvider implementation that can provide formatting information for the objects in args
. provider
può essere uno degli elementi seguenti:provider
can be any of the following:
CultureInfoOggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.A CultureInfo object that provides culture-specific formatting information.
NumberFormatInfoOggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura per i valori numerici in
args
.A NumberFormatInfo object that provides culture-specific formatting information for numeric values inargs
.DateTimeFormatInfoOggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura per i valori di data e ora in
args
.A DateTimeFormatInfo object that provides culture-specific formatting information for date and time values inargs
.Implementazione personalizzata IFormatProvider che fornisce informazioni sulla formattazione per uno o più oggetti in
args
.A custom IFormatProvider implementation that provides formatting information for one or more of the objects inargs
. In genere, tale implementazione implementa anche l' ICustomFormatter interfaccia.Typically, such an implementation also implements the ICustomFormatter interface. Nel secondo esempio della sezione seguente viene illustrata una StringBuilder.AppendFormat(IFormatProvider, String, Object[]) chiamata al metodo con un' IFormatProvider implementazione personalizzata.The second example in the next section illustrates an StringBuilder.AppendFormat(IFormatProvider, String, Object[]) method call with a custom IFormatProvider implementation.
Se il provider
parametro è null
, le informazioni sul provider di formato vengono ottenute dalle impostazioni cultura correnti.If the provider
parameter is null
, format provider information is obtained from the current culture.
args
rappresenta gli oggetti da formattare.args
represents the objects to be formatted. Ogni elemento di formato in format
viene sostituito con la rappresentazione di stringa dell'oggetto corrispondente in args
.Each format item in format
is replaced with the string representation of the corresponding object in args
. Se l'elemento di formato include formatString
e l'oggetto corrispondente in args
implementa l' IFormattable interfaccia, args[index].ToString(formatString, provider)
definisce la formattazione.If the format item includes formatString
and the corresponding object in args
implements the IFormattable interface, then args[index].ToString(formatString, provider)
defines the formatting. In caso contrario, args[index].ToString()
definisce la formattazione.Otherwise, args[index].ToString()
defines the formatting.
Note per i chiamanti
In .NET Core e in .NET Framework 4,0 e versioni successive, quando si crea un'istanza dell' StringBuilder oggetto chiamando il StringBuilder(Int32, Int32) costruttore, sia la lunghezza che la capacità dell' StringBuilder istanza possono superare il valore della MaxCapacity Proprietà.In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. Questa situazione può verificarsi in particolare quando si chiamano i Append(String) AppendFormat(String, Object) metodi e per aggiungere stringhe di piccole dimensioni.This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.
Vedi anche
- Formattazione di tipi in .NETFormatting Types in .NET
- Formattazione compositaComposite Formatting
- Procedura: Definire e usare provider di formati numerici personalizzatiHow to: Define and Use Custom Numeric Format Providers
- Stringhe di formato numerico standardStandard Numeric Format Strings
- Stringhe di formato numerico personalizzatoCustom Numeric Format Strings
- Stringhe di formato di data e ora standardStandard Date and Time Format Strings
- Stringhe di formato di data e ora personalizzatoCustom Date and Time Format Strings
- Stringhe di formato TimeSpan standardStandard TimeSpan Format Strings
- Stringhe di formato TimeSpan personalizzateCustom TimeSpan Format Strings
- Stringhe di formato di enumerazioneEnumeration Format Strings
Si applica a
AppendFormat(String, Object, Object)
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di uno dei due argomenti.Each format item is replaced by the string representation of either of two arguments.
public:
System::Text::StringBuilder ^ AppendFormat(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1);
public System.Text.StringBuilder AppendFormat (string format, object arg0, object arg1);
public System.Text.StringBuilder AppendFormat (string format, object? arg0, object? arg1);
member this.AppendFormat : string * obj * obj -> System.Text.StringBuilder
Public Function AppendFormat (format As String, arg0 As Object, arg1 As Object) As StringBuilder
Parametri
- format
- String
Stringa in formato composito.A composite format string.
- arg0
- Object
Primo oggetto da formattare.The first object to format.
- arg1
- Object
Secondo oggetto da formattare.The second object to format.
Restituisce
Riferimento a questa istanza con format
accodato.A reference to this instance with format
appended. Ogni elemento di formato in format
viene sostituito dalla rappresentazione di stringa dell'argomento dell'oggetto corrispondente.Each format item in format
is replaced by the string representation of the corresponding object argument.
Eccezioni
format
è null
.format
is null
.
format
non è valido.format
is invalid.
-oppure--or-
L'indice di un elemento di formato è minore di 0 (zero) oppure maggiore o uguale a 2 (due).The index of a format item is less than 0 (zero), or greater than or equal to 2.
La lunghezza della stringa espansa supererebbe MaxCapacity.The length of the expanded string would exceed MaxCapacity.
Esempio
Nell'esempio seguente viene illustrato il AppendFormat metodo.The following example demonstrates the AppendFormat method.
using namespace System;
using namespace System::Text;
using namespace System::Globalization;
void Show( StringBuilder^ sbs )
{
Console::WriteLine( sbs );
sbs->Length = 0;
}
int main()
{
StringBuilder^ sb = gcnew StringBuilder;
int var1 = 111;
float var2 = 2.22F;
String^ var3 = "abcd";
array<Object^>^var4 = {3,4.4,(Char)'X'};
Console::WriteLine();
Console::WriteLine( "StringBuilder.AppendFormat method:" );
sb->AppendFormat( "1) {0}", var1 );
Show( sb );
sb->AppendFormat( "2) {0}, {1}", var1, var2 );
Show( sb );
sb->AppendFormat( "3) {0}, {1}, {2}", var1, var2, var3 );
Show( sb );
sb->AppendFormat( "4) {0}, {1}, {2}", var4 );
Show( sb );
CultureInfo^ ci = gcnew CultureInfo( "es-ES",true );
array<Object^>^temp1 = {var2};
sb->AppendFormat( ci, "5) {0}", temp1 );
Show( sb );
}
/*
This example produces the following results:
StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
using System;
using System.Text;
using System.Globalization;
class Sample
{
static StringBuilder sb = new StringBuilder();
public static void Main()
{
int var1 = 111;
float var2 = 2.22F;
string var3 = "abcd";
object[] var4 = {3, 4.4, 'X'};
Console.WriteLine();
Console.WriteLine("StringBuilder.AppendFormat method:");
sb.AppendFormat("1) {0}", var1);
Show(sb);
sb.AppendFormat("2) {0}, {1}", var1, var2);
Show(sb);
sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3);
Show(sb);
sb.AppendFormat("4) {0}, {1}, {2}", var4);
Show(sb);
CultureInfo ci = new CultureInfo("es-ES", true);
sb.AppendFormat(ci, "5) {0}", var2);
Show(sb);
}
public static void Show(StringBuilder sbs)
{
Console.WriteLine(sbs.ToString());
sb.Length = 0;
}
}
/*
This example produces the following results:
StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
Imports System.Text
Imports System.Globalization
Class Sample
Private Shared sb As New StringBuilder()
Public Shared Sub Main()
Dim var1 As Integer = 111
Dim var2 As Single = 2.22F
Dim var3 As String = "abcd"
Dim var4 As Object() = {3, 4.4, "X"c}
Console.WriteLine()
Console.WriteLine("StringBuilder.AppendFormat method:")
sb.AppendFormat("1) {0}", var1)
Show(sb)
sb.AppendFormat("2) {0}, {1}", var1, var2)
Show(sb)
sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3)
Show(sb)
sb.AppendFormat("4) {0}, {1}, {2}", var4)
Show(sb)
Dim ci As New CultureInfo("es-ES", True)
sb.AppendFormat(ci, "5) {0}", var2)
Show(sb)
End Sub
Public Shared Sub Show(sbs As StringBuilder)
Console.WriteLine(sbs.ToString())
sb.Length = 0
End Sub
End Class
'
'This example produces the following results:
'
'StringBuilder.AppendFormat method:
'1) 111
'2) 111, 2.22
'3) 111, 2.22, abcd
'4) 3, 4.4, X
'5) 2,22
Commenti
Questo metodo utilizza la funzionalità di formattazione composita del .NET Framework per convertire il valore di un oggetto nella relativa rappresentazione testuale e incorporare tale rappresentazione nell' StringBuilder oggetto corrente.This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in the current StringBuilder object.
Il format
parametro è costituito da zero o più esecuzioni di testo combinate con zero o più segnaposto indicizzati, denominati elementi di formato, che corrispondono a arg0
e arg1
, i due oggetti nell'elenco di parametri di questo metodo.The format
parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to arg0
and arg1
, the two objects in the parameter list of this method. Il processo di formattazione sostituisce ogni elemento di formato con la rappresentazione di stringa dell'oggetto corrispondente.The formatting process replaces each format item with the string representation of the corresponding object.
La sintassi di un elemento di formato è la seguente:The syntax of a format item is as follows:
{index[,length] [:FormatString]}{index[,length][:formatString]}
Gli elementi tra parentesi quadre sono facoltativi.Elements in square brackets are optional. La tabella seguente descrive i singoli elementi.The following table describes each element.
ElementoElement | DescrizioneDescription |
---|---|
indexindex | Posizione in base zero nell'elenco di parametri dell'oggetto da formattare.The zero-based position in the parameter list of the object to be formatted. Se l'oggetto specificato da index è null , l'elemento di formato viene sostituito da String.Empty .If the object specified by index is null , the format item is replaced by String.Empty. Se non è presente alcun parametro nella posizione dell' Indice , FormatException viene generata un'eccezione.If there is no parameter in the index position, a FormatException is thrown. |
,lunghezza,length | Numero minimo di caratteri nella rappresentazione di stringa del parametro.The minimum number of characters in the string representation of the parameter. Se positivo, il parametro è allineato a destra; Se negativo, è allineato a sinistra.If positive, the parameter is right-aligned; if negative, it is left-aligned. |
:FormatString:formatString | Stringa di formato standard o personalizzata supportata dal parametro.A standard or custom format string that is supported by the parameter. |
Nota
Per le stringhe di formato standard e personalizzate usate con i valori di data e ora, vedere stringhe di formato di data e ora standard e stringhe di formato di data e ora personalizzate.For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. Per le stringhe di formato standard e personalizzate usate con i valori numerici, vedere stringhe di formato numerico standard e stringhe di formato numerico personalizzate.For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. Per le stringhe di formato standard usate con le enumerazioni, vedere stringhe di formato di enumerazione.For the standard format strings used with enumerations, see Enumeration Format Strings.
arg0
e arg1
rappresentano gli oggetti da formattare.arg0
and arg1
represent the objects to be formatted. Ogni elemento di formato in format
viene sostituito con la rappresentazione di stringa di arg0
o arg1
.Each format item in format
is replaced with the string representation of either arg0
or arg1
. Se l'elemento di formato include formatString
e l'oggetto corrispondente implementa l' IFormattable interfaccia, arg
x .ToString(formatString, provider)
definisce la formattazione, dove x è l'indice dell'argomento.If the format item includes formatString
and the corresponding object implements the IFormattable interface, then arg
x.ToString(formatString, provider)
defines the formatting, where x is the index of the argument. In caso contrario, arg
x .ToString()
definisce la formattazione.Otherwise, arg
x.ToString()
defines the formatting.
Se la stringa assegnata a format
è "Grazie per la donazione di {0: # # # #} lattine di cibo per la nostra organizzazione caritatevole".If the string assigned to format
is "Thank you for your donation of {0:####} cans of food to our charitable organization." e arg0
è un numero intero con valore 10, il valore restituito sarà "Grazie per la donazione di 10 lattine di cibo alla nostra organizzazione caritatevole".and arg0
is an integer with the value 10, the return value will be "Thank you for your donation of 10 cans of food to our charitable organization."
Note per i chiamanti
In .NET Core e in .NET Framework 4,0 e versioni successive, quando si crea un'istanza dell' StringBuilder oggetto chiamando il StringBuilder(Int32, Int32) costruttore, sia la lunghezza che la capacità dell' StringBuilder istanza possono superare il valore della MaxCapacity Proprietà.In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. Questa situazione può verificarsi in particolare quando si chiamano i Append(String) AppendFormat(String, Object) metodi e per aggiungere stringhe di piccole dimensioni.This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.
Vedi anche
- Formattazione di tipi in .NETFormatting Types in .NET
- Formattazione compositaComposite Formatting
- Stringhe di formato numerico standardStandard Numeric Format Strings
- Stringhe di formato numerico personalizzatoCustom Numeric Format Strings
- Stringhe di formato di data e ora standardStandard Date and Time Format Strings
- Stringhe di formato di data e ora personalizzatoCustom Date and Time Format Strings
- Stringhe di formato TimeSpan standardStandard TimeSpan Format Strings
- Stringhe di formato TimeSpan personalizzateCustom TimeSpan Format Strings
- Stringhe di formato di enumerazioneEnumeration Format Strings
Si applica a
AppendFormat(IFormatProvider, String, Object, Object)
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di uno di due argomenti usando un provider del formato specificato.Each format item is replaced by the string representation of either of two arguments using a specified format provider.
public:
System::Text::StringBuilder ^ AppendFormat(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0, System::Object ^ arg1);
public System.Text.StringBuilder AppendFormat (IFormatProvider provider, string format, object arg0, object arg1);
public System.Text.StringBuilder? AppendFormat (IFormatProvider provider, string? format, object arg0, object arg1);
member this.AppendFormat : IFormatProvider * string * obj * obj -> System.Text.StringBuilder
Public Function AppendFormat (provider As IFormatProvider, format As String, arg0 As Object, arg1 As Object) As StringBuilder
Parametri
- provider
- IFormatProvider
Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.An object that supplies culture-specific formatting information.
- format
- String
Stringa in formato composito.A composite format string.
- arg0
- Object
Primo oggetto da formattare.The first object to format.
- arg1
- Object
Secondo oggetto da formattare.The second object to format.
Restituisce
Riferimento a questa istanza dopo il completamento dell'operazione di accodamento.A reference to this instance after the append operation has completed. Al termine dell'operazione di accodamento, questa istanza conterrà tutti i dati esistenti prima dell'operazione, seguiti da una copia di format
in cui le specifiche di formato vengono sostituite dalla rappresentazione di stringa dell'argomento dell'oggetto corrispondente.After the append operation, this instance contains any data that existed before the operation, suffixed by a copy of format
where any format specification is replaced by the string representation of the corresponding object argument.
Eccezioni
format
è null
.format
is null
.
format
non è valido.format
is invalid.
-oppure--or-
L'indice di un elemento di formato è minore di 0 (zero) oppure maggiore o uguale a 2 (due).The index of a format item is less than 0 (zero), or greater than or equal to 2 (two).
La lunghezza della stringa espansa supererebbe MaxCapacity.The length of the expanded string would exceed MaxCapacity.
Esempio
Nell'esempio seguente viene usato il AppendFormat(IFormatProvider, String, Object, Object) metodo per visualizzare i dati relativi a tempo e temperatura archiviati in un Dictionary<TKey,TValue> oggetto generico.The following example uses the AppendFormat(IFormatProvider, String, Object, Object) method to display time and temperature data stored in a generic Dictionary<TKey,TValue> object. Si noti che la stringa di formato contiene tre elementi di formato, sebbene ci siano solo oggetti da formattare.Note that the format string has three format items, although there are only to objects to format. Questo perché il primo oggetto dell'elenco (un valore di data e ora) viene usato da due elementi di formato: il primo elemento di formato Visualizza l'ora e il secondo Visualizza la data.This is because the first object in the list (a date and time value) is used by two format items: The first format item displays the time, and the second displays the date.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
public class Example
{
public static void Main()
{
CultureInfo culture = new CultureInfo("en-US");
StringBuilder sb = new StringBuilder();
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);
sb.AppendLine("Temperature Information:\n");
foreach (var item in temperatureInfo)
{
sb.AppendFormat(culture,
"Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F\n",
item.Key, item.Value);
}
Console.WriteLine(sb.ToString());
}
}
// 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
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Text
Module Example
Public Sub Main()
Dim culture As New CultureInfo("en-US")
Dim sb As New StringBuilder()
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)
sb.AppendLine("Temperature Information:").AppendLine()
For Each item In temperatureInfo
sb.AppendFormat(culture,
"Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F",
item.Key, item.Value).AppendLine()
Next
Console.WriteLine(sb.ToString())
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
Commenti
Questo metodo utilizza la funzionalità di formattazione composita del .NET Framework per convertire il valore di un oggetto nella relativa rappresentazione testuale e incorporare tale rappresentazione nell' StringBuilder oggetto corrente.This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in the current StringBuilder object.
Il format
parametro è costituito da zero o più esecuzioni di testo combinate con zero o più segnaposto indicizzati, denominati elementi di formato, che corrispondono a oggetti nell'elenco di parametri di questo metodo.The format
parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to objects in the parameter list of this method. Il processo di formattazione sostituisce ogni elemento di formato con la rappresentazione di stringa dell'oggetto corrispondente.The formatting process replaces each format item with the string representation of the corresponding object.
La sintassi di un elemento di formato è la seguente:The syntax of a format item is as follows:
{index[,length] [:FormatString]}{index[,length][:formatString]}
Gli elementi tra parentesi quadre sono facoltativi.Elements in square brackets are optional. La tabella seguente descrive i singoli elementi.The following table describes each element.
ElementoElement | DescrizioneDescription |
---|---|
indexindex | Posizione in base zero nell'elenco di parametri dell'oggetto da formattare.The zero-based position in the parameter list of the object to be formatted. Se l'oggetto specificato da index è null , l'elemento di formato viene sostituito da String.Empty .If the object specified by index is null , the format item is replaced by String.Empty. Se non è presente alcun parametro nella posizione dell' Indice , FormatException viene generata un'eccezione.If there is no parameter in the index position, a FormatException is thrown. |
,lunghezza,length | Numero minimo di caratteri nella rappresentazione di stringa del parametro.The minimum number of characters in the string representation of the parameter. Se positivo, il parametro è allineato a destra; Se negativo, è allineato a sinistra.If positive, the parameter is right-aligned; if negative, it is left-aligned. |
:FormatString:formatString | Stringa di formato standard o personalizzata supportata dal parametro.A standard or custom format string that is supported by the parameter. |
Nota
Per le stringhe di formato standard e personalizzate usate con i valori di data e ora, vedere stringhe di formato di data e ora standard e stringhe di formato di data e ora personalizzate.For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. Per le stringhe di formato standard e personalizzate usate con i valori numerici, vedere stringhe di formato numerico standard e stringhe di formato numerico personalizzate.For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. Per le stringhe di formato standard usate con le enumerazioni, vedere stringhe di formato di enumerazione.For the standard format strings used with enumerations, see Enumeration Format Strings.
Il provider
parametro specifica un' IFormatProvider implementazione di che può fornire informazioni sulla formattazione per arg0
e arg1
.The provider
parameter specifies an IFormatProvider implementation that can provide formatting information for arg0
and arg1
. provider
può essere uno degli elementi seguenti:provider
can be any of the following:
CultureInfoOggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura.A CultureInfo object that provides culture-specific formatting information.
NumberFormatInfoOggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura per
arg0
oarg1
se sono valori numerici.A NumberFormatInfo object that provides culture-specific formatting information forarg0
orarg1
if they are numeric values.DateTimeFormatInfoOggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura per
arg0
oarg1
se sono valori di data e ora.A DateTimeFormatInfo object that provides culture-specific formatting information forarg0
orarg1
if they are date and time values.Implementazione personalizzata IFormatProvider che fornisce informazioni sulla formattazione per
arg0
earg1
.A custom IFormatProvider implementation that provides formatting information forarg0
andarg1
. In genere, tale implementazione implementa anche l' ICustomFormatter interfaccia.Typically, such an implementation also implements the ICustomFormatter interface.
Se il provider
parametro è null
, le informazioni sul provider di formato vengono ottenute dalle impostazioni cultura correnti.If the provider
parameter is null
, format provider information is obtained from the current culture.
arg0
e arg1
rappresentano gli oggetti da formattare.arg0
and arg1
represent the objects to be formatted. Ogni elemento di formato in format
viene sostituito con la rappresentazione di stringa dell'oggetto con l'indice corrispondente.Each format item in format
is replaced with the string representation of the object that has the corresponding index. Se l'elemento di formato include formatString
e l'argomento corrispondente implementa l' IFormattable interfaccia, il metodo dell'argomento ToString(formatString, provider)
definisce la formattazione.If the format item includes formatString
and the corresponding argument implements the IFormattable interface, then the argument's ToString(formatString, provider)
method defines the formatting. In caso contrario, il ToString()
metodo dell'argomento definisce la formattazione.Otherwise, the argument's ToString()
method defines the formatting.
Note per i chiamanti
Nell'.NET Core e in .NET Framework 4,0 e versioni successive, quando si crea un'istanza dell' StringBuilder oggetto chiamando il StringBuilder(Int32, Int32) costruttore, sia la lunghezza che la capacità dell' StringBuilder istanza possono superare il valore della MaxCapacity Proprietà.IIn .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. Questa situazione può verificarsi in particolare quando si chiamano i Append(String) AppendFormat(String, Object) metodi e per aggiungere stringhe di piccole dimensioni.This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.
Vedi anche
- Formattazione di tipi in .NETFormatting Types in .NET
- Formattazione compositaComposite Formatting
- Procedura: Definire e usare provider di formati numerici personalizzatiHow to: Define and Use Custom Numeric Format Providers
- Stringhe di formato numerico standardStandard Numeric Format Strings
- Stringhe di formato numerico personalizzatoCustom Numeric Format Strings
- Stringhe di formato di data e ora standardStandard Date and Time Format Strings
- Stringhe di formato di data e ora personalizzatoCustom Date and Time Format Strings
- Stringhe di formato TimeSpan standardStandard TimeSpan Format Strings
- Stringhe di formato TimeSpan personalizzateCustom TimeSpan Format Strings
- Stringhe di formato di enumerazioneEnumeration Format Strings
Si applica a
AppendFormat(String, Object, Object, Object)
Accoda la stringa restituita dall'elaborazione di una stringa in formato composito, che contiene zero o più elementi di formato, a questa istanza.Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Ogni elemento di formato viene sostituito dalla rappresentazione di stringa di uno dei tre argomenti.Each format item is replaced by the string representation of either of three arguments.
public:
System::Text::StringBuilder ^ AppendFormat(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2);
public System.Text.StringBuilder AppendFormat (string format, object arg0, object arg1, object arg2);
public System.Text.StringBuilder? AppendFormat (string? format, object arg0, object arg1, object arg2);
member this.AppendFormat : string * obj * obj * obj -> System.Text.StringBuilder
Public Function AppendFormat (format As String, arg0 As Object, arg1 As Object, arg2 As Object) As StringBuilder
Parametri
- format
- String
Stringa in formato composito.A composite format string.
- arg0
- Object
Primo oggetto da formattare.The first object to format.
- arg1
- Object
Secondo oggetto da formattare.The second object to format.
- arg2
- Object
Terzo oggetto da formattare.The third object to format.
Restituisce
Riferimento a questa istanza con format
accodato.A reference to this instance with format
appended. Ogni elemento di formato in format
viene sostituito dalla rappresentazione di stringa dell'argomento dell'oggetto corrispondente.Each format item in format
is replaced by the string representation of the corresponding object argument.
Eccezioni
format
è null
.format
is null
.
format
non è valido.format
is invalid.
-oppure--or-
L'indice di un elemento di formato è minore di 0 (zero) oppure maggiore o uguale a 3 (due).The index of a format item is less than 0 (zero), or greater than or equal to 3.
La lunghezza della stringa espansa supererebbe MaxCapacity.The length of the expanded string would exceed MaxCapacity.
Esempio
Nell'esempio seguente viene illustrato il AppendFormat metodo.The following example demonstrates the AppendFormat method.
using namespace System;
using namespace System::Text;
using namespace System::Globalization;
void Show( StringBuilder^ sbs )
{
Console::WriteLine( sbs );
sbs->Length = 0;
}
int main()
{
StringBuilder^ sb = gcnew StringBuilder;
int var1 = 111;
float var2 = 2.22F;
String^ var3 = "abcd";
array<Object^>^var4 = {3,4.4,(Char)'X'};
Console::WriteLine();
Console::WriteLine( "StringBuilder.AppendFormat method:" );
sb->AppendFormat( "1) {0}", var1 );
Show( sb );
sb->AppendFormat( "2) {0}, {1}", var1, var2 );
Show( sb );
sb->AppendFormat( "3) {0}, {1}, {2}", var1, var2, var3 );
Show( sb );
sb->AppendFormat( "4) {0}, {1}, {2}", var4 );
Show( sb );
CultureInfo^ ci = gcnew CultureInfo( "es-ES",true );
array<Object^>^temp1 = {var2};
sb->AppendFormat( ci, "5) {0}", temp1 );
Show( sb );
}
/*
This example produces the following results:
StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
using System;
using System.Text;
using System.Globalization;
class Sample
{
static StringBuilder sb = new StringBuilder();
public static void Main()
{
int var1 = 111;
float var2 = 2.22F;
string var3 = "abcd";
object[] var4 = {3, 4.4, 'X'};
Console.WriteLine();
Console.WriteLine("StringBuilder.AppendFormat method:");
sb.AppendFormat("1) {0}", var1);
Show(sb);
sb.AppendFormat("2) {0}, {1}", var1, var2);
Show(sb);
sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3);
Show(sb);
sb.AppendFormat("4) {0}, {1}, {2}", var4);
Show(sb);
CultureInfo ci = new CultureInfo("es-ES", true);
sb.AppendFormat(ci, "5) {0}", var2);
Show(sb);
}
public static void Show(StringBuilder sbs)
{
Console.WriteLine(sbs.ToString());
sb.Length = 0;
}
}
/*
This example produces the following results:
StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
Imports System.Text
Imports System.Globalization
Class Sample
Private Shared sb As New StringBuilder()
Public Shared Sub Main()
Dim var1 As Integer = 111
Dim var2 As Single = 2.22F
Dim var3 As String = "abcd"
Dim var4 As Object() = {3, 4.4, "X"c}
Console.WriteLine()
Console.WriteLine("StringBuilder.AppendFormat method:")
sb.AppendFormat("1) {0}", var1)
Show(sb)
sb.AppendFormat("2) {0}, {1}", var1, var2)
Show(sb)
sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3)
Show(sb)
sb.AppendFormat("4) {0}, {1}, {2}", var4)
Show(sb)
Dim ci As New CultureInfo("es-ES", True)
sb.AppendFormat(ci, "5) {0}", var2)
Show(sb)
End Sub
Public Shared Sub Show(sbs As StringBuilder)
Console.WriteLine(sbs.ToString())
sb.Length = 0
End Sub
End Class
'
'This example produces the following results:
'
'StringBuilder.AppendFormat method:
'1) 111
'2) 111, 2.22
'3) 111, 2.22, abcd
'4) 3, 4.4, X
'5) 2,22
Commenti
Questo metodo utilizza la funzionalità di formattazione composita del .NET Framework per convertire il valore di un oggetto nella relativa rappresentazione testuale e incorporare tale rappresentazione nell' StringBuilder oggetto corrente.This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in the current StringBuilder object.
Il format
parametro è costituito da zero o più esecuzioni di testo combinate con zero o più segnaposto indicizzati, denominati elementi di formato, che corrispondono a arg0
tramite arg2
, gli oggetti nell'elenco di parametri di questo metodo.The format
parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to arg0
through arg2
, the objects in the parameter list of this method. Il processo di formattazione sostituisce ogni elemento di formato con la rappresentazione di stringa dell'oggetto corrispondente.The formatting process replaces each format item with the string representation of the corresponding object.
La sintassi di un elemento di formato è la seguente:The syntax of a format item is as follows:
{index[,length] [:FormatString]}{index[,length][:formatString]}
Gli elementi tra parentesi quadre sono facoltativi.Elements in square brackets are optional. La tabella seguente descrive i singoli elementi.The following table describes each element.
ElementoElement | DescrizioneDescription |
---|---|
indexindex | Posizione in base zero nell'elenco di parametri dell'oggetto da formattare.The zero-based position in the parameter list of the object to be formatted. Se l'oggetto specificato da index è null , l'elemento di formato viene sostituito da String.Empty .If the object specified by index is null , the format item is replaced by String.Empty. Se non è presente alcun parametro nella posizione dell' Indice , FormatException viene generata un'eccezione.If there is no parameter in the index position, a FormatException is thrown. |
,lunghezza,length | Numero minimo di caratteri nella rappresentazione di stringa del parametro.The minimum number of characters in the string representation of the parameter. Se positivo, il parametro è allineato a destra; Se negativo, è allineato a sinistra.If positive, the parameter is right-aligned; if negative, it is left-aligned. |
:FormatString:formatString | Stringa di formato standard o personalizzata supportata dal parametro.A standard or custom format string that is supported by the parameter. |
Nota
Per le stringhe di formato standard e personalizzate usate con i valori di data e ora, vedere stringhe di formato di data e ora standard e stringhe di formato di data e ora personalizzate.For the standard and custom format strings used with date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings. Per le stringhe di formato standard e personalizzate usate con i valori numerici, vedere stringhe di formato numerico standard e stringhe di formato numerico personalizzate.For the standard and custom format strings used with numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. Per le stringhe di formato standard usate con le enumerazioni, vedere stringhe di formato di enumerazione.For the standard format strings used with enumerations, see Enumeration Format Strings.
arg0
, arg1
e arg2
rappresentano gli oggetti da formattare.arg0
, arg1
, and arg2
represent the objects to be formatted. Ogni elemento di formato in format
viene sostituito con la rappresentazione di stringa di arg0
, arg1
o arg2
, a seconda dell'indice dell'elemento di formato.Each format item in format
is replaced with the string representation of either arg0
, arg1
, or arg2
, depending on the index of the format item. Se l'elemento di formato include formatString
e l'oggetto corrispondente in args
implementa l' IFormattable interfaccia, arg
x .ToString(formatString, null)
definisce la formattazione, dove x è l'indice dell'argomento.If the format item includes formatString
and the corresponding object in args
implements the IFormattable interface, then arg
x.ToString(formatString, null)
defines the formatting, where x is the index of the argument. In caso contrario, arg
x .ToString()
definisce la formattazione.Otherwise, arg
x.ToString()
defines the formatting.
Se la stringa assegnata a format
è "Grazie per la donazione di {0: # # # #} lattine di cibo per la nostra organizzazione caritatevole".If the string assigned to format
is "Thank you for your donation of {0:####} cans of food to our charitable organization." e arg0
è un numero intero con valore 10, il valore restituito sarà "Grazie per la donazione di 10 lattine di cibo alla nostra organizzazione caritatevole".and arg0
is an integer with the value 10, the return value will be "Thank you for your donation of 10 cans of food to our charitable organization."
Note per i chiamanti
In .NET Core e in .NET Framework 4,0 e versioni successive, quando si crea un'istanza dell' StringBuilder oggetto chiamando il StringBuilder(Int32, Int32) costruttore, sia la lunghezza che la capacità dell' StringBuilder istanza possono superare il valore della MaxCapacity Proprietà.In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. Questa situazione può verificarsi in particolare quando si chiamano i Append(String) AppendFormat(String, Object) metodi e per aggiungere stringhe di piccole dimensioni.This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.
Vedi anche
- Formattazione di tipi in .NETFormatting Types in .NET
- Formattazione compositaComposite Formatting
- Stringhe di formato numerico standardStandard Numeric Format Strings
- Stringhe di formato numerico personalizzatoCustom Numeric Format Strings
- Stringhe di formato di data e ora standardStandard Date and Time Format Strings
- Stringhe di formato di data e ora personalizzatoCustom Date and Time Format Strings
- Stringhe di formato TimeSpan standardStandard TimeSpan Format Strings
- Stringhe di formato TimeSpan personalizzateCustom TimeSpan Format Strings
- Stringhe di formato di enumerazioneEnumeration Format Strings