IFormattable Rozhraní
Definice
Poskytuje funkce pro formátování hodnoty objektu na řetězcovou reprezentaci.Provides functionality to format the value of an object into a string representation.
public interface class IFormattable
public interface IFormattable
[System.Runtime.InteropServices.ComVisible(true)]
public interface IFormattable
type IFormattable = interface
[<System.Runtime.InteropServices.ComVisible(true)>]
type IFormattable = interface
Public Interface IFormattable
- Odvozené
- Atributy
Příklady
Následující příklad definuje Temperature třídu, která implementuje IFormattable rozhraní.The following example defines a Temperature class that implements the IFormattable interface. Třída podporuje čtyři specifikátory formátu: "G" a "C", což značí, že teplota se má zobrazit ve stupních Celsia; "F", což znamená, že se teplota zobrazuje ve stupních Fahrenheita; a "K", což značí, že se má teplota zobrazit v kelvinech.The class supports four format specifiers: "G" and "C", which indicate that the temperature is to be displayed in Celsius; "F", which indicates that the temperature is to be displayed in Fahrenheit; and "K", which indicates that the temperature is to be displayed in Kelvin. Kromě toho IFormattable.ToString implementace také může zpracovat řetězec formátu, který je null nebo prázdný.In addition, the IFormattable.ToString implementation also can handle a format string that is null or empty. Další dvě ToString metody definované Temperature třídou jednoduše zabalí volání IFormattable.ToString implementace.The other two ToString methods defined by the Temperature class simply wrap a call to the IFormattable.ToString implementation.
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
Následující příklad volá IFormattable.ToString implementaci buď přímo, nebo pomocí složeného formátovacího řetězce.The following example then calls the IFormattable.ToString implementation either directly or by using a composite format string.
public class Example
{
public static void Main()
{
// Use composite formatting with format string in the format item.
Temperature temp1 = new Temperature(0);
Console.WriteLine("{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)\n", temp1);
// Use composite formatting with a format provider.
temp1 = new Temperature(-40);
Console.WriteLine(String.Format(CultureInfo.CurrentCulture, "{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)", temp1));
Console.WriteLine(String.Format(new CultureInfo("fr-FR"), "{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)\n", temp1));
// Call ToString method with format string.
temp1 = new Temperature(32);
Console.WriteLine("{0} (Celsius) = {1} (Kelvin) = {2} (Fahrenheit)\n",
temp1.ToString("C"), temp1.ToString("K"), temp1.ToString("F"));
// Call ToString with format string and format provider
temp1 = new Temperature(100) ;
NumberFormatInfo current = NumberFormatInfo.CurrentInfo;
CultureInfo nl = new CultureInfo("nl-NL");
Console.WriteLine("{0} (Celsius) = {1} (Kelvin) = {2} (Fahrenheit)",
temp1.ToString("C", current), temp1.ToString("K", current), temp1.ToString("F", current));
Console.WriteLine("{0} (Celsius) = {1} (Kelvin) = {2} (Fahrenheit)",
temp1.ToString("C", nl), temp1.ToString("K", nl), temp1.ToString("F", nl));
}
}
// The example displays the following output:
// 0.00 °C (Celsius) = 273.15 K (Kelvin) = 32.00 °F (Fahrenheit)
//
// -40.00 °C (Celsius) = 233.15 K (Kelvin) = -40.00 °F (Fahrenheit)
// -40,00 °C (Celsius) = 233,15 K (Kelvin) = -40,00 °F (Fahrenheit)
//
// 32.00 °C (Celsius) = 305.15 K (Kelvin) = 89.60 °F (Fahrenheit)
//
// 100.00 °C (Celsius) = 373.15 K (Kelvin) = 212.00 °F (Fahrenheit)
// 100,00 °C (Celsius) = 373,15 K (Kelvin) = 212,00 °F (Fahrenheit)
Module Example
Public Sub Main()
' Use composite formatting with format string in the format item.
Dim temp1 As New Temperature(0)
Console.WriteLine("{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)", temp1)
Console.WriteLine()
' Use composite formatting with a format provider.
temp1 = New Temperature(-40)
Console.WriteLine(String.Format(CultureInfo.CurrentCulture, "{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)", temp1))
Console.WriteLine(String.Format(New CultureInfo("fr-FR"), "{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)", temp1))
Console.WriteLine()
' Call ToString method with format string.
temp1 = New Temperature(32)
Console.WriteLine("{0} (Celsius) = {1} (Kelvin) = {2} (Fahrenheit)", _
temp1.ToString("C"), temp1.ToString("K"), temp1.ToString("F"))
Console.WriteLine()
' Call ToString with format string and format provider
temp1 = New Temperature(100)
Dim current As NumberFormatInfo = NumberFormatInfo.CurrentInfo
Dim nl As New CultureInfo("nl-NL")
Console.WriteLine("{0} (Celsius) = {1} (Kelvin) = {2} (Fahrenheit)", _
temp1.ToString("C", current), temp1.ToString("K", current), temp1.ToString("F", current))
Console.WriteLine("{0} (Celsius) = {1} (Kelvin) = {2} (Fahrenheit)", _
temp1.ToString("C", nl), temp1.ToString("K", nl), temp1.ToString("F", nl))
End Sub
End Module
' The example displays the following output:
' 0.00 °C (Celsius) = 273.15 K (Kelvin) = 32.00 °F (Fahrenheit)
'
' -40.00 °C (Celsius) = 233.15 K (Kelvin) = -40.00 °F (Fahrenheit)
' -40,00 °C (Celsius) = 233,15 K (Kelvin) = -40,00 °F (Fahrenheit)
'
' 32.00 °C (Celsius) = 305.15 K (Kelvin) = 89.60 °F (Fahrenheit)
'
' 100.00 °C (Celsius) = 373.15 K (Kelvin) = 212.00 °F (Fahrenheit)
' 100,00 °C (Celsius) = 373,15 K (Kelvin) = 212,00 °F (Fahrenheit)
Poznámky
IFormattableRozhraní převede objekt na jeho řetězcovou reprezentaci na základě formátovacího řetězce a poskytovatele formátu.The IFormattable interface converts an object to its string representation based on a format string and a format provider.
Formátovací řetězec obvykle definuje obecný vzhled objektu.A format string typically defines the general appearance of an object. .NET Framework například podporuje následující:For example, the .NET Framework supports the following:
Standardní formátovací řetězce pro formátování hodnot výčtu (viz řetězce formátu výčtu).Standard format strings for formatting enumeration values (see Enumeration Format Strings).
Standardní a vlastní formátovací řetězce pro formátování číselných hodnot (viz Standardní číselné formátovací řetězce a řetězce vlastního číselného formátu).Standard and custom format strings for formatting numeric values (see Standard Numeric Format Strings and Custom Numeric Format Strings).
Standardní a vlastní formátovací řetězce pro formátování hodnot data a času (viz Standardní řetězce formátu data a času a Vlastní řetězce formátu data a času).Standard and custom format strings for formatting date and time values (see Standard Date and Time Format Strings and Custom Date and Time Format Strings).
Standardní a vlastní řetězce formátu pro časové intervaly formátování (viz Standardní řetězce formátu TimeSpan a Vlastní řetězce formátu TimeSpan).Standard and custom format strings for formatting time intervals (see Standard TimeSpan Format Strings and Custom TimeSpan Format Strings).
Můžete také definovat vlastní řetězce formátu pro podporu formátování typů definovaných aplikací.You can also define your own format strings to support formatting of your application-defined types.
Zprostředkovatel formátu vrátí objekt formátování, který obvykle definuje symboly používané při převodu objektu na jeho řetězcovou reprezentaci.A format provider returns a formatting object that typically defines the symbols used in converting an object to its string representation. Například Pokud převedete číslo na hodnotu měny, zprostředkovatel formátu definuje symbol měny, který se zobrazí ve výsledném řetězci.For example, when you convert a number to a currency value, a format provider defines the currency symbol that appears in the result string. .NET Framework definuje tři poskytovatele formátu:The .NET Framework defines three format providers:
System.Globalization.CultureInfoTřída, která vrací buď NumberFormatInfo objekt pro formátování číselných hodnot, nebo DateTimeFormatInfo objekt pro formátování hodnot data a času.The System.Globalization.CultureInfo class, which returns either a NumberFormatInfo object for formatting numeric values, or a DateTimeFormatInfo object for formatting date and time values.
System.Globalization.NumberFormatInfoTřída, která vrací instanci sebe sama pro formátování číselných hodnot.The System.Globalization.NumberFormatInfo class, which returns an instance of itself for formatting numeric values.
System.Globalization.DateTimeFormatInfoTřída, která vrací instanci sebe sama pro formátování hodnot data a času.The System.Globalization.DateTimeFormatInfo class, which returns an instance of itself for formatting date and time values.
Kromě toho můžete definovat vlastní poskytovatele formátu, který bude poskytovat informace specifické pro konkrétní jazykovou verzi nebo informace specifické pro konkrétní prostředí, použité při formátování.In addition, you can define your own custom format providers to supply culture-specific, profession-specific, or industry-specific information used in formatting. Další informace o implementaci vlastního formátování pomocí vlastního poskytovatele formátu naleznete v tématu ICustomFormatter .For more information about implementing custom formatting by using a custom format provider, see ICustomFormatter.
IFormattableRozhraní definuje jedinou metodu, ToString která poskytuje formátovací služby pro implementující typ.The IFormattable interface defines a single method, ToString, that supplies formatting services for the implementing type. ToStringMetodu lze volat přímo.The ToString method can be called directly. Kromě toho je volána automaticky Convert.ToString(Object) Convert.ToString(Object, IFormatProvider) metodami a a metodami, které používají funkci složeného formátování v .NET Framework.In addition, it is 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. Console.WriteLine(String, Object)Mezi další metody patří, String.Format a StringBuilder.AppendFormat(String, Object) , mimo jiné.Such methods include Console.WriteLine(String, Object), String.Format, and StringBuilder.AppendFormat(String, Object), among others. ToStringMetoda je volána pro každou položku formátu v řetězci formátu metody.The ToString method is called for each format item in the method's format string.
IFormattableRozhraní je implementováno pomocí základních datových typů.The IFormattable interface is implemented by the base data types.
Poznámky pro implementátory
Třídy, které vyžadují větší kontrolu nad formátováním řetězců, než ToString() poskytuje, by měly implementovat IFormattable .Classes that require more control over the formatting of strings than ToString() provides should implement IFormattable.
Třída, která implementuje, IFormattable musí podporovat specifikátor formátu "G" (Obecné).A class that implements IFormattable must support the "G" (general) format specifier. Kromě specifikátoru "G" může třída definovat seznam specifikátorů formátu, které podporuje.Besides the "G" specifier, the class can define the list of format specifiers that it supports. Kromě toho musí být třída připravena pro zpracování specifikátoru formátu, který je null .In addition, the class must be prepared to handle a format specifier that is null. Další informace o formátování a formátování kódů najdete v tématu typy formátování .For more information about formatting and formatting codes, see Formatting Types
Metody
| ToString(String, IFormatProvider) |
Zformátuje hodnotu aktuální instance pomocí zadaného formátu.Formats the value of the current instance using the specified format. |