IFormattable.ToString(String, IFormatProvider) Methode
Definition
Formatiert den Wert der aktuellen Instanz mit dem angegebenen Format.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
Parameter
- format
- String
Das zu verwendende Format.The format to use.
- oder --or-
Ein NULL-Verweis (Nothing
in Visual Basic), um das Standardformat zu verwenden, das für den Typ der IFormattable-Implementierung definiert ist.A null reference (Nothing
in Visual Basic) to use the default format defined for the type of the IFormattable implementation.
- formatProvider
- IFormatProvider
Der Anbieter, der zum Formatieren des Werts verwendet werden soll.The provider to use to format the value.
- oder --or-
Ein NULL-Verweis (Nothing
in Visual Basic), um die Zahlenformatinformationen aus dem aktuellen Gebietsschema des Betriebssystems abzurufen.A null reference (Nothing
in Visual Basic) to obtain the numeric format information from the current locale setting of the operating system.
Gibt zurück
Der Wert der aktuellen Instanz im angegebenen Format.The value of the current instance in the specified format.
Beispiele
Im folgenden Beispiel wird eine Temperature
Klasse veranschaulicht, die die- ToString Methode implementiert.The following example demonstrates a Temperature
class that implements the ToString method. Dieses Codebeispiel ist Teil eines größeren Beispiels, das für die-Klasse bereitgestellt wird IFormattable .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
Hinweise
Die- ToString Methode konvertiert einen Wert in eine Zeichen folgen Darstellung, die auf verschiedene Weise ausgedrückt werden kann.The ToString method converts a value to a string representation that can be expressed in multiple ways. Das genaue Format hängt von bestimmten Symbolen oder der angegebenen Reihenfolge ab, die durch bestimmte Kulturen, Berufe oder Branchen definiert ist.Its precise format depends on specific symbols or a specified order defined by specific cultures, professions, or industries. Sie können die-Methode direkt aufzurufen.You can call the method directly. Sie wird auch automatisch von der Convert.ToString(Object) -Methode und der- Convert.ToString(Object, IFormatProvider) Methode sowie von Methoden aufgerufen, die das Feature für die kombinierte Formatierung in der .NET Framework verwenden, wie z String.Format(String, Object[]) . b Console.WriteLine(String, Object[]) ., und 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[]). (Weitere Informationen finden Sie unter kombinierte Formatierung.)(For more information, see Composite Formatting.)
Kombinierte Formatierungs Methoden bezeichnen die ToString Methode einmal für jedes Format Element in einer Format Zeichenfolge.Composite formatting methods call the ToString method once for each format item in a format string. Die Parameter, die an die-Methode weitergegeben werden, hängen wie folgt von der spezifischen Formatierungs Methode, die aufgerufen wird, und vom Inhalt des Format Elements ab: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:
Wenn das Format Element keine Format Zeichenfolge enthält (z. b. wenn das Format Element einfach ist
{0}
), wird esnull
als Wert des- System.String Parameters übergeben.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.Wenn das Format Element eine Format Zeichenfolge (z. b.
{0:G}
) enthält, wird diese Format Zeichenfolge als Wert des- System.String Parameters übergeben.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.Wenn der ursprüngliche Methoden Aufrufwert keinen- System.IFormatProvider Parameter enthält, CultureInfo.CurrentCulture wird als Wert des- System.IFormatProvider Parameters übergeben.If the original method call does not include an System.IFormatProvider parameter, CultureInfo.CurrentCulture is passed as the value of the System.IFormatProvider parameter.
Wenn der ursprüngliche Methoden Aufrufwert einen- System.IFormatProvider Parameter enthält, wird der im Methodenaufrufe angegebene Anbieter als Wert des- System.IFormatProvider Parameters übergeben.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.
Hinweis
Die Implementierung eines Objekts ToString wird nur durch kombinierte Formatierungs Methoden aufgerufen, wenn Ihnen kein ICustomFormatter Format Anbieter übermittelt wird oder wenn die- Format Methode des benutzerdefinierten Format Anbieters zurückgibt 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
.
Die .NET Framework enthält drei Format Anbieter, die alle die- IFormatProvider Schnittstelle implementieren:The .NET Framework includes three format providers, all of which implement the IFormatProvider interface:
NumberFormatInfo liefert numerische Formatierungsinformationen, z. b. die Zeichen, die für Dezimal-und Gruppen Trennzeichen verwendet werden sollen, sowie die Rechtschreibung und Platzierung von Währungs Symbolen in Währungswerten.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 liefert Datums-und zeitbezogene Formatierungsinformationen, wie z. b. die Position des Monats, den Tag und das Jahr in einem Datums Muster.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 enthält die Standard Formatierungsinformationen in einer bestimmten Kultur, einschließlich der numerischen Formatinformationen und Datums-und zeitbezogenen Formatierungsinformationen.CultureInfo contains the default formatting information in a specific culture, including the numeric format information, and date-related and time-related formatting information.
Außerdem können Sie einen eigenen benutzerdefinierten Format Anbieter definieren.In addition, you can define your own custom format provider.
Hinweise für Ausführende
Die- ToString(String, IFormatProvider) Methode muss den Format Bezeichner "G" (allgemein) unterstützen.The ToString(String, IFormatProvider) method must support the "G" (general) format specifier. Neben dem "G"-Spezifizierer kann die-Klasse die Liste der Format Bezeichner definieren, die Sie unterstützt.Besides the "G" specifier, the class can define the list of format specifiers that it supports. Außerdem muss die Klasse darauf vorbereitet sein, einen Format Bezeichner zu verarbeiten, der ist null
.In addition, the class must be prepared to handle a format specifier that is null
. Weitere Informationen zu Formatierungs-und Formatierungscodes finden Sie unter Formatieren von Typen.For more information about formatting and formatting codes, see Formatting Types.