IFormattable Rozhraní
Definice
Důležité
Některé informace platí pro předběžně vydaný produkt, který se může zásadně změnit, než ho výrobce nebo autor vydá. Microsoft neposkytuje žádné záruky, výslovné ani předpokládané, týkající se zde uváděných informací.
Poskytuje funkce pro formátování hodnoty objektu do řetězcové reprezentace.
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í. Třída podporuje čtyři specifikátory formátu: "G" a "C", což znamená, že teplota se má zobrazit ve stupních Celsia; "F", což označuje, že teplota se má zobrazit v fahrenheitu; a "K", což označuje, že teplota se má zobrazit v Kelvinu. Kromě toho IFormattable.ToString implementace dokáže zpracovat také formátovací řetězec, který je nebo je null prázdný. Další dvě ToString metody definované Temperature třídou jednoduše zabalí volání implementace IFormattable.ToString .
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));
}
}
}
open System
open System.Globalization
type Temperature(temperature: decimal) =
do
if temperature < -273.15M then
raise (ArgumentOutOfRangeException $"{temperature} is less than absolute zero.")
member _.Celsius =
temperature
member _.Fahrenheit =
temperature * 9M / 5M + 32M
member _.Kelvin =
temperature + 273.15m
override this.ToString() =
this.ToString("G", CultureInfo.CurrentCulture)
member this.ToString(format) =
this.ToString(format, CultureInfo.CurrentCulture)
member this.ToString(format, provider: IFormatProvider) =
let format =
if String.IsNullOrEmpty format then "G"
else format
let provider =
if isNull provider then
CultureInfo.CurrentCulture :> IFormatProvider
else provider
match format.ToUpperInvariant() with
| "G" | "C" ->
temperature.ToString("F2", provider) + " °C"
| "F" ->
this.Fahrenheit.ToString("F2", provider) + " °F"
| "K" ->
this.Kelvin.ToString("F2", provider) + " K"
| _ ->
raise (FormatException $"The {format} format string is not supported.")
interface IFormattable with
member this.ToString(format, provider) = this.ToString(format, provider)
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 pak volá implementaci IFormattable.ToString buď přímo, nebo pomocí řetězce složeného formátu.
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)
open System
open System.Globalization
[<EntryPoint>]
let main _ =
// Use composite formatting with format string in the format item.
let temp1 = Temperature 0
Console.WriteLine("{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)\n", temp1)
// Use composite formatting with a format provider.
let temp1 = Temperature -40
String.Format(CultureInfo.CurrentCulture, "{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)", temp1)
|> printfn "%s"
String.Format(CultureInfo "fr-FR", "{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)\n", temp1)
|> printfn "%s"
// Call ToString method with format string.
let temp1 = 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
let temp1 = Temperature 100
let current = NumberFormatInfo.CurrentInfo
let nl = 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))
0
// 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
Rozhraní IFormattable převede objekt na jeho řetězcové vyjádření na základě formátovací řetězec a zprostředkovatele formátu.
Formátovací řetězec obvykle definuje obecný vzhled objektu. Rozhraní .NET Framework například podporuje následující:
Standardní formátovací řetězce pro formátování hodnot výčtu (viz Výčtové formátovací řetězce).
Standardní a vlastní formátovací řetězce pro formátování číselných hodnot (viz standardní řetězce číselného formátu a vlastní řetězce číselného formátu).
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).
Standardní a vlastní formátovací řetězce pro formátování časových intervalů (viz Standardní řetězce formátu TimeSpan a vlastní řetězce formátu TimeSpan).
Můžete také definovat vlastní formátovací řetězce, které podporují formátování typů definovaných aplikací.
Zprostředkovatel formátu vrátí objekt formátování, který obvykle definuje symboly použité při převodu objektu na jeho řetězcové vyjádření. Když například převedete číslo na hodnotu měny, poskytovatel formátu definuje symbol měny, který se zobrazí ve výsledném řetězci. Rozhraní .NET Framework definuje tři zprostředkovatele formátu:
Třída System.Globalization.CultureInfo , která vrací NumberFormatInfo objekt pro formátování číselných hodnot nebo DateTimeFormatInfo objekt pro formátování hodnot data a času.
Třída System.Globalization.NumberFormatInfo , která vrací instanci sama pro formátování číselných hodnot.
Třída System.Globalization.DateTimeFormatInfo , která vrací instanci sama pro formátování hodnot data a času.
Kromě toho můžete definovat vlastní poskytovatele formátů, které poskytují informace specifické pro jazykovou verzi, konkrétní povolání nebo informace specifické pro dané odvětví použité ve formátování. Další informace o implementaci vlastního formátování pomocí zprostředkovatele vlastního formátu naleznete v tématu ICustomFormatter.
Rozhraní IFormattable definuje jednu metodu, ToStringkterá poskytuje formátovací služby pro implementující typ. Metodu ToString lze volat přímo. Kromě toho se volá automaticky metodami Convert.ToString(Object) a Convert.ToString(Object, IFormatProvider) metodami, které používají funkci složeného formátování v rozhraní .NET Framework. Mezi tyto metody patří Console.WriteLine(String, Object), String.Formata StringBuilder.AppendFormat(String, Object), mimo jiné. Metoda ToString se volá pro každou položku formátu v řetězci formátu metody.
Rozhraní IFormattable je implementováno základními datovými typy.
Poznámky pro implementátory
Třídy, které vyžadují větší kontrolu nad formátováním řetězců, než ToString() je třeba implementovat IFormattable.
Třída, která implementuje IFormattable , musí podporovat specifikátor formátu "G" (obecný). Kromě specifikátoru "G" může třída definovat seznam specifikátorů formátu, které podporuje. Kromě toho musí být třída připravena na zpracování specifikátoru formátu, který je null. Další informace o formátování a formátování kódů naleznete v tématu Typy formátování
Metody
| Name | Description |
|---|---|
| ToString(String, IFormatProvider) |
Naformátuje hodnotu aktuální instance pomocí zadaného formátu. |