IFormattable.ToString(String, IFormatProvider) Metodo
Definizione
Formatta il valore dell'istanza corrente usando il formato specificato.Formats the value of the current instance using the specified format.
public:
System::String ^ ToString(System::String ^ format, IFormatProvider ^ formatProvider);
public string ToString (string format, IFormatProvider formatProvider);
public string ToString (string? format, IFormatProvider? formatProvider);
abstract member ToString : string * IFormatProvider -> string
Public Function ToString (format As String, formatProvider As IFormatProvider) As String
Parametri
- format
- String
Formato da usare.The format to use.
-oppure--or-
Riferimento null (Nothing
in Visual Basic) per usare il formato predefinito per il tipo dell'implementazione di IFormattable.A null reference (Nothing
in Visual Basic) to use the default format defined for the type of the IFormattable implementation.
- formatProvider
- IFormatProvider
Provider da utilizzare per formattare il valore.The provider to use to format the value.
-oppure--or-
Riferimento null (Nothing
in Visual Basic) per ottenere le informazioni sul formato numerico dalle impostazioni locali correnti del sistema operativo.A null reference (Nothing
in Visual Basic) to obtain the numeric format information from the current locale setting of the operating system.
Restituisce
Valore dell'istanza corrente nel formato specificato.The value of the current instance in the specified format.
Esempio
Nell'esempio seguente viene illustrata una Temperature
classe che implementa il ToString metodo.The following example demonstrates a Temperature
class that implements the ToString method. Questo esempio di codice fa parte di un esempio più ampio fornito per la IFormattable classe.This code example is part of a larger example provided for the IFormattable class.
using System;
using System.Globalization;
public class Temperature : IFormattable
{
private decimal temp;
public Temperature(decimal temperature)
{
if (temperature < -273.15m)
throw new ArgumentOutOfRangeException(String.Format("{0} is less than absolute zero.",
temperature));
this.temp = temperature;
}
public decimal Celsius
{
get { return temp; }
}
public decimal Fahrenheit
{
get { return temp * 9 / 5 + 32; }
}
public decimal Kelvin
{
get { return temp + 273.15m; }
}
public override string ToString()
{
return this.ToString("G", CultureInfo.CurrentCulture);
}
public string ToString(string format)
{
return this.ToString(format, CultureInfo.CurrentCulture);
}
public string ToString(string format, IFormatProvider provider)
{
if (String.IsNullOrEmpty(format)) format = "G";
if (provider == null) provider = CultureInfo.CurrentCulture;
switch (format.ToUpperInvariant())
{
case "G":
case "C":
return temp.ToString("F2", provider) + " °C";
case "F":
return Fahrenheit.ToString("F2", provider) + " °F";
case "K":
return Kelvin.ToString("F2", provider) + " K";
default:
throw new FormatException(String.Format("The {0} format string is not supported.", format));
}
}
}
Imports System.Globalization
Public Class Temperature : Implements IFormattable
Private temp As Decimal
Public Sub New(temperature As Decimal)
If temperature < -273.15 Then _
Throw New ArgumentOutOfRangeException(String.Format("{0} is less than absolute zero.", _
temperature))
Me.temp = temperature
End Sub
Public ReadOnly Property Celsius As Decimal
Get
Return temp
End Get
End Property
Public ReadOnly Property Fahrenheit As Decimal
Get
Return temp * 9 / 5 + 32
End Get
End Property
Public ReadOnly Property Kelvin As Decimal
Get
Return temp + 273.15d
End Get
End Property
Public Overrides Function ToString() As String
Return Me.ToString("G", CultureInfo.CurrentCulture)
End Function
Public Overloads Function ToString(fmt As String) As String
Return Me.ToString(fmt, CultureInfo.CurrentCulture)
End Function
Public Overloads Function ToString(fmt As String, provider As IFormatProvider) _
As String _
Implements IFormattable.ToString
If String.IsNullOrEmpty(fmt) Then fmt = "G"
If provider Is Nothing Then provider = CultureInfo.CurrentCulture
Select Case fmt.ToUpperInvariant()
Case "G", "C"
Return temp.ToString("F2", provider) + " °C"
Case "F"
Return Fahrenheit.ToString("F2", provider) + " °F"
Case "K"
Return Kelvin.ToString("F2", provider) + " K"
Case Else
Throw New FormatException(String.Format("The {0} format string is not supported.", fmt))
End Select
End Function
End Class
Commenti
Il ToString metodo converte un valore in una rappresentazione di stringa che può essere espressa in diversi modi.The ToString method converts a value to a string representation that can be expressed in multiple ways. Il formato preciso dipende da simboli specifici o da un ordine specificato definito da impostazioni cultura, professioni o settori specifici.Its precise format depends on specific symbols or a specified order defined by specific cultures, professions, or industries. È possibile chiamare direttamente il metodo.You can call the method directly. Viene inoltre chiamato automaticamente dai metodi Convert.ToString(Object) e Convert.ToString(Object, IFormatProvider) e dai metodi che utilizzano la funzionalità di formattazione composita in .NET Framework, come String.Format(String, Object[]), Console.WriteLine(String, Object[]) e StringBuilder.AppendFormat(String, Object[]).It is also called automatically by the Convert.ToString(Object) and Convert.ToString(Object, IFormatProvider) methods, and by methods that use the composite formatting feature in the .NET Framework, such as String.Format(String, Object[]), Console.WriteLine(String, Object[]), and StringBuilder.AppendFormat(String, Object[]). (Per altre informazioni, vedere formattazione composita).(For more information, see Composite Formatting.)
I metodi di formattazione composita chiamano il ToString Metodo una volta per ogni elemento di formato in una stringa di formato.Composite formatting methods call the ToString method once for each format item in a format string. I parametri passati al metodo dipendono dal metodo di formattazione specifico chiamato e dal contenuto dell'elemento di formato, come indicato di seguito:The parameters passed to the method depend on the specific formatting method that is called and on the content of the format item, as follows:
Se l'elemento di formato non include una stringa di formato, ad esempio se l'elemento di formato è semplicemente
{0}
, viene passatonull
come valore del System.String parametro.If the format item does not include a format string (for example, if the format item is simply{0}
), it is passednull
as the value of the System.String parameter.Se l'elemento di formato include una stringa di formato (ad esempio,
{0:G}
), tale stringa di formato viene passata come valore del System.String parametro.If the format item includes a format string (for example,{0:G}
), that format string is passed as the value of the System.String parameter.Se la chiamata al metodo originale non include un System.IFormatProvider parametro, CultureInfo.CurrentCulture viene passato come valore del System.IFormatProvider parametro.If the original method call does not include an System.IFormatProvider parameter, CultureInfo.CurrentCulture is passed as the value of the System.IFormatProvider parameter.
Se la chiamata al metodo originale include un System.IFormatProvider parametro, il provider fornito nella chiamata al metodo viene passato come valore del System.IFormatProvider parametro.If the original method call includes an System.IFormatProvider parameter, the provider that is supplied in the method call is passed as the value of the System.IFormatProvider parameter.
Nota
L'implementazione di un oggetto ToString viene chiamata dai metodi di formattazione composita solo se non viene passato un ICustomFormatter provider di formato o se il Format metodo del provider di formato personalizzato restituisce null
.An object's ToString implementation is called by composite formatting methods only if they are not passed an ICustomFormatter format provider, or if the Format method of the custom format provider returns null
.
Il .NET Framework include tre provider di formato, che implementano tutti l' IFormatProvider interfaccia:The .NET Framework includes three format providers, all of which implement the IFormatProvider interface:
NumberFormatInfo fornisce informazioni di formattazione numerica, ad esempio i caratteri da utilizzare per i separatori decimali e di gruppo, nonché l'ortografia e la posizione dei simboli di valuta nei valori monetari.NumberFormatInfo supplies numeric formatting information, such as the characters to use for decimal and group separators, and the spelling and placement of currency symbols in monetary values.
DateTimeFormatInfo fornisce informazioni di formattazione relative alla data e all'ora, ad esempio la posizione del mese, il giorno e l'anno in un modello di data.DateTimeFormatInfo supplies date-related and time-related formatting information, such as the position of the month, the day, and the year in a date pattern.
CultureInfo contiene le informazioni di formattazione predefinite in impostazioni cultura specifiche, incluse le informazioni sul formato numerico e le informazioni di formattazione relative alla data e all'ora.CultureInfo contains the default formatting information in a specific culture, including the numeric format information, and date-related and time-related formatting information.
Inoltre, è possibile definire un provider di formato personalizzato.In addition, you can define your own custom format provider.
Note per gli implementatori
Il ToString(String, IFormatProvider) metodo deve supportare l'identificatore di formato "G" (generale).The ToString(String, IFormatProvider) method must support the "G" (general) format specifier. Oltre all'identificatore "G", la classe può definire l'elenco degli identificatori di formato supportati.Besides the "G" specifier, the class can define the list of format specifiers that it supports. Inoltre, la classe deve essere preparata a gestire un identificatore di formato null
.In addition, the class must be prepared to handle a format specifier that is null
. Per ulteriori informazioni sulla formattazione e i codici di formattazione, vedere formattazione di tipi.For more information about formatting and formatting codes, see Formatting Types.