String.Format Metoda
Definice
Převede hodnotu objektů na řetězce na základě zadaných formátů a vloží je do jiného řetězce.Converts the value of objects to strings based on the formats specified and inserts them into another string.
Pokud s touto metodou začínáte String.Format , přečtěte si téma Začínáme s metodou String. Format , kde najdete rychlý přehled.If you are new to the String.Format method, see the Get started with the String.Format method section for a quick overview.
Obecnou dokumentaci k metodě najdete v části poznámky String.Format .See the Remarks section for general documentation for the String.Format method.
Přetížení
| Format(String, Object) |
Nahradí jednu nebo více položek formátu v řetězci řetězcovou reprezentací zadaného objektu.Replaces one or more format items in a string with the string representation of a specified object. |
| Format(String, Object[]) |
Nahradí položku formátu v zadaném řetězci řetězcovou reprezentací odpovídajícího objektu v zadaném poli.Replaces the format item in a specified string with the string representation of a corresponding object in a specified array. |
| Format(IFormatProvider, String, Object) |
Nahradí položku formátu nebo položky v zadaném řetězci řetězcovou reprezentací odpovídajícího objektu.Replaces the format item or items in a specified string with the string representation of the corresponding object. Parametr poskytuje informace o formátování specifické pro jazykovou verzi.A parameter supplies culture-specific formatting information. |
| Format(IFormatProvider, String, Object[]) |
Nahradí položky formátu v řetězci řetězcovými reprezentacemi odpovídajících objektů v zadaném poli.Replaces the format items in a string with the string representations of corresponding objects in a specified array. Parametr poskytuje informace o formátování specifické pro jazykovou verzi.A parameter supplies culture-specific formatting information. |
| Format(String, Object, Object) |
Nahradí položky formátu v řetězci řetězcovou reprezentací dvou zadaných objektů.Replaces the format items in a string with the string representation of two specified objects. |
| Format(IFormatProvider, String, Object, Object) |
Nahradí položky formátu v řetězci řetězcovou reprezentací dvou zadaných objektů.Replaces the format items in a string with the string representation of two specified objects. Parametr poskytuje informace o formátování specifické pro jazykovou verzi.A parameter supplies culture-specific formatting information. |
| Format(String, Object, Object, Object) |
Nahradí položky formátu v řetězci řetězcovou reprezentací tří zadaných objektů.Replaces the format items in a string with the string representation of three specified objects. |
| Format(IFormatProvider, String, Object, Object, Object) |
Nahradí položky formátu v řetězci řetězcovou reprezentací tří zadaných objektů.Replaces the format items in a string with the string representation of three specified objects. Parametr poskytuje informace o formátování specifické pro jazykovou verzi.An parameter supplies culture-specific formatting information. |
Příklady
Mnohé příklady, které volají metodu, jsou provázány Format prostřednictvím oddílu poznámky tohoto článku.Numerous examples that call the Format method are interspersed through the Remarks section of this article.
Můžete si také stáhnout kompletní sadu String.Format příkladů, které jsou součástí projektu .NET Core pro C#.You can also download a complete set of String.Format examples, which are included a .NET Core project for C#.
Níže jsou uvedeny některé příklady, které jsou součástí článku:The following are some of the examples included in the article:
Vytvořit formátovací řetězecCreate a format string
Vložení řetězceInserting a string
Položka formátuThe format item
Položky formátu, které mají stejný indexFormat items that have the same index
Řízení formátovaného výstupuControl formatted output
Řízení formátováníControlling formatting
Řízení rozestupůControlling spacing
Řízení zarovnáníControlling alignment
Řízení počtu integrálních číslicControlling the number of integral digits
Řízení počtu číslic po oddělovači desetinných místControlling the number of digits after the decimal separator
Zahrnutí literálních složených závorek do výsledného řetězceIncluding literal braces in a result string
Vytváření řetězců formátu – rozlišovat jazykové verzeMake format strings culture-sensitive
Formátování zohledňující jazykovou verziCulture-sensitive formatting
Přizpůsobení operace formátováníCustomize the formatting operation
Vlastní operace formátováníA custom formatting operation
Modul pro zachycení a formátování římských číslicAn intercept provider and Roman numeral formatter
Poznámky
Důležité
Namísto volání metody String. Format nebo použití složených formátovacích řetězcůmůžete použít interpolované řetězce , pokud je váš jazyk podporuje.Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. Interpolovaná řetězcová událost je řetězec, který obsahuje interpolované výrazy.An interpolated string is a string that contains interpolated expressions. Každý interpolující výraz je vyřešen s hodnotou výrazu a je zahrnut ve výsledném řetězci při přiřazení řetězce.Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. Další informace naleznete v tématu interpolace řetězce (Referenční dokumentace jazyka C#) a interpolované řetězce (Visual Basic odkaz).For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).
V této části:In this section:
Začněte s metodou String. FormatGet started with the String.Format method
Kterou metodu můžu zavolat?Which method do I call?
Metoda Format v krátkém formátuThe Format method in brief
Položka formátuThe Format item
Způsob formátování argumentůHow arguments are formatted
Formátovat položky, které mají stejný indexFormat items that have the same index
Formátování a jazyková verzeFormatting and culture
Vlastní operace formátováníCustom formatting operations
String. Format Q & AString.Format Q & A
Začněte s metodou String. FormatGet started with the String.Format method
Použijte, String.Format Pokud potřebujete vložit hodnotu objektu, proměnné nebo výrazu do jiného řetězce.Use String.Format if you need to insert the value of an object, variable, or expression into another string. Můžete například vložit hodnotu Decimal hodnoty do řetězce, aby se zobrazila uživateli jako jeden řetězec:For example, you can insert the value of a Decimal value into a string to display it to the user as a single string:
Decimal pricePerOunce = (Decimal)17.36;
String^ s = String::Format("The current price is {0} per ounce.",
pricePerOunce);
// Result: The current price is 17.36 per ounce.
Decimal pricePerOunce = 17.36m;
String s = String.Format("The current price is {0} per ounce.",
pricePerOunce);
Console.WriteLine(s);
// Result: The current price is 17.36 per ounce.
Dim pricePerOunce As Decimal = 17.36d
Dim s As String = String.Format("The current price is {0} per ounce.",
pricePerOunce)
' Result: The current price is 17.36 per ounce.
A můžete řídit formátování těchto hodnot:And you can control that value's formatting:
Decimal pricePerOunce = (Decimal)17.36;
String^ s = String::Format("The current price is {0:C2} per ounce.",
pricePerOunce);
// Result if current culture is en-US:
// The current price is $17.36 per ounce.
Decimal pricePerOunce = 17.36m;
String s = String.Format("The current price is {0:C2} per ounce.",
pricePerOunce);
Console.WriteLine(s);
// Result if current culture is en-US:
// The current price is $17.36 per ounce.
Dim pricePerOunce As Decimal = 17.36d
Dim s As String = String.Format("The current price is {0:C2} per ounce.",
pricePerOunce)
' Result if current culture is en-US:
' The current price is $17.36 per ounce.
Kromě formátování můžete také ovládat zarovnání a mezery.Besides formatting, you can also control alignment and spacing.
Vložit řetězecInsert a string
String.Format začíná řetězcem formátu následovaným jedním nebo více objekty nebo výrazy, které budou převedeny na řetězce a vloženy na určené místo v řetězci formátu.String.Format starts with a format string, followed by one or more objects or expressions that will be converted to strings and inserted at a specified place in the format string. Například:For example:
Decimal temp = (Decimal)20.4;
String^ s = String::Format("The temperature is {0}°C.", temp);
Console::WriteLine(s);
// Displays 'The temperature is 20.4°C.'
decimal temp = 20.4m;
string s = String.Format("The temperature is {0}°C.", temp);
Console.WriteLine(s);
// Displays 'The temperature is 20.4°C.'
Dim temp As Decimal = 20.4d
Dim s As String = String.Format("The temperature is {0}°C.", temp)
Console.WriteLine(s)
' Displays 'The temperature is 20.4°C.'
{0}Řetězec ve formátu je položka formátu.The {0} in the format string is a format item. 0 je index objektu, jehož řetězcová hodnota bude vložena na tuto pozici.0 is the index of the object whose string value will be inserted at that position. (Indexy začínají na 0.) Pokud objekt, který má být vložen, není řetězec, ToString je jeho metoda volána pro jeho převedení na jeden před vložením do výsledného řetězce.(Indexes start at 0.) If the object to be inserted is not a string, its ToString method is called to convert it to one before inserting it in the result string.
Tady je další příklad, který používá dvě položky formátu a dva objekty v seznamu objektů:Here's another example that uses two format items and two objects in the object list:
String^ s = String::Format("At {0}, the temperature is {1}°C.",
DateTime::Now, 20.4);
// Output similar to: 'At 4/10/2015 9:29:41 AM, the temperature is 20.4°C.'
string s = String.Format("At {0}, the temperature is {1}°C.",
DateTime.Now, 20.4);
Console.WriteLine(s);
// Output similar to: 'At 4/10/2015 9:29:41 AM, the temperature is 20.4°C.'
Dim s As String = String.Format("At {0}, the temperature is {1}°C.",
Date.Now, 20.4)
' Output similar to: 'At 4/10/2015 9:29:41 AM, the temperature is 20.4°C.'
Podle potřeby můžete mít tolik položek formátu a tolik objektů v seznamu objektů, pokud má index každé položky formátu shodný objekt v seznamu objektů.You can have as many format items and as many objects in the object list as you want, as long as the index of every format item has a matching object in the object list. Nemusíte se také starat o to, které přetížení zavoláte. kompilátor pro vás vybere vhodný.You also don't have to worry about which overload you call; the compiler will select the appropriate one for you.
Formátování ovládacího prvkuControl formatting
Můžete postupovat podle indexu v položce formátu s formátovacím řetězcem pro řízení způsobu formátování objektu.You can follow the index in a format item with a format string to control how an object is formatted. Například {0:d} použije řetězec formátu "d" na první objekt v seznamu objektů.For example, {0:d} applies the "d" format string to the first object in the object list. Tady je příklad s jedním objektem a dvěma položkami formátu:Here is an example with a single object and two format items:
String^ s = String::Format("It is now {0:d} at {0:t}",
DateTime::Now);
// Output similar to: 'It is now 4/10/2015 at 10:04 AM'
string s = String.Format("It is now {0:d} at {0:t}", DateTime.Now);
Console.WriteLine(s);
// Output similar to: 'It is now 4/10/2015 at 10:04 AM'
Dim s As String = String.Format("It is now {0:d} at {0:t}",
Date.Now)
' Output similar to: 'It is now 4/10/2015 at 10:04 AM'
Mnoho typů podporuje řetězce formátu, včetně všech číselných typů ( standardní i vlastní řetězce formátu), všech hodnot data a času (standardní a vlastní formátovací řetězce) a časových intervalů ( standardní i vlastní řetězce formátu), všech výčtových typů výčtůa identifikátorů GUID.A number of types support format strings, including all numeric types (both standard and custom format strings), all dates and times (both standard and custom format strings) and time intervals (both standard and custom format strings), all enumeration types enumeration types, and GUIDs. Můžete také přidat podporu pro řetězce formátu do vlastních typů.You can also add support for format strings to your own types.
Mezery mezi ovládacími prvkyControl spacing
Můžete definovat šířku řetězce, který je vložen do výsledného řetězce pomocí syntaxe {0,12} , například, která vloží řetězec o 12 znacích.You can define the width of the string that is inserted into the result string by using syntax such as {0,12}, which inserts a 12-character string. V tomto případě je řetězcová reprezentace prvního objektu zarovnána vpravo v poli 12 znaků.In this case, the string representation of the first object is right-aligned in the 12-character field. (Pokud řetězcové vyjádření prvního objektu je delší než 12 znaků, ale Upřednostňovaná šířka pole se ignoruje a celý řetězec je vložen do výsledného řetězce.)(If the string representation of the first object is more than 12 characters in length, though, the preferred field width is ignored, and the entire string is inserted into the result string.)
Následující příklad definuje pole o 6 znaků pro uchování řetězce "Year" a některých roků a také pole o 15 znacích pro uchování řetězce "populace" a některých dat populace.The following example defines a 6-character field to hold the string "Year" and some year strings, as well as an 15-character field to hold the string "Population" and some population data. Všimněte si, že znaky jsou zarovnány vpravo v poli.Note that the characters are right-aligned in the field.
array<int>^ years = { 2013, 2014, 2015 };
array<int>^ population = { 1025632, 1105967, 1148203 };
StringBuiler^ sb = gcnew StringBuilder();
sb->Append(String::Format("{0,6} {1,15}\n\n", "Year", "Population"));
for(int index = 0; index < years->Length; index++)
sb->AppendFormat("{0,6} {1,15:N0}\n",
years[index], population[index]);
// Result:
// Year Population
//
// 2013 1,025,632
// 2014 1,105,967
// 2015 1,148,203
int[] years = { 2013, 2014, 2015 };
int[] population = { 1025632, 1105967, 1148203 };
var sb = new System.Text.StringBuilder();
sb.Append(String.Format("{0,6} {1,15}\n\n", "Year", "Population"));
for (int index = 0; index < years.Length; index++)
sb.Append(String.Format("{0,6} {1,15:N0}\n", years[index], population[index]));
Console.WriteLine(sb);
// Result:
// Year Population
//
// 2013 1,025,632
// 2014 1,105,967
// 2015 1,148,203
Dim years() As Integer = { 2013, 2014, 2015 }
Dim population() As Integer = { 1025632, 1105967, 1148203 }
Dim sb As New StringBuilder()
sb.Append(String.Format("{0,6} {1,15}{2}{2}",
"Year", "Population", vbCrLf))
For index As Integer = 0 To years.Length - 1
sb.AppendFormat("{0,6} {1,15:N0}{2}",
years(index), population(index), vbCrLf)
Next
' Result:
' Year Population
'
' 2013 1,025,632
' 2014 1,105,967
' 2015 1,148,203
Zarovnání ovládacího prvkuControl alignment
Ve výchozím nastavení jsou řetězce v rámci svého pole zarovnány vpravo, pokud zadáte šířku pole.By default, strings are right-aligned within their field if you specify a field width. Chcete-li v poli zarovnat řetězce doleva, je třeba nastavit šířku pole na záporné znaménko, například {0,-12} pro definování 12 znaků zarovnané vlevo.To left-align strings in a field, you preface the field width with a negative sign, such as {0,-12} to define a 12-character left-aligned field.
Následující příklad je podobný předchozímu, s tím rozdílem, že vlevo zarovnává oba popisky a data.The following example is similar to the previous one, except that it left-aligns both labels and data.
array<int>^ years = { 2013, 2014, 2015 };
array<int>^ population = { 1025632, 1105967, 1148203 };
String^ s = String::Format("{0,-10} {1,-10}\n\n", "Year", "Population");
for(int index = 0; index < years->Length; index++)
s += String::Format("{0,-10} {1,-10:N0}\n",
years[index], population[index]);
// Result:
// Year Population
//
// 2013 1,025,632
// 2014 1,105,967
// 2015 1,148,203
int[] years = { 2013, 2014, 2015 };
int[] population = { 1025632, 1105967, 1148203 };
String s = String.Format("{0,-10} {1,-10}\n\n", "Year", "Population");
for(int index = 0; index < years.Length; index++)
s += String.Format("{0,-10} {1,-10:N0}\n",
years[index], population[index]);
Console.WriteLine($"\n{s}");
// Result:
// Year Population
//
// 2013 1,025,632
// 2014 1,105,967
// 2015 1,148,203
Dim years() As Integer = { 2013, 2014, 2015 }
Dim population() As Integer = { 1025632, 1105967, 1148203 }
Dim s As String = String.Format("{0,-10} {1,-10}{2}{2}",
"Year", "Population", vbCrLf)
For index As Integer = 0 To years.Length - 1
s += String.Format("{0,-10} {1,-10:N0}{2}",
years(index), population(index), vbCrLf)
Next
' Result:
' Year Population
'
' 2013 1,025,632
' 2014 1,105,967
' 2015 1,148,203
String.Format využívá funkci složeného formátování.String.Format makes use of the composite formatting feature. Další informace najdete v tématu složené formátování.For more information, see Composite Formatting.
Jakou metodu mám volat?Which method do I call?
| ZáměrTo | CallCall |
|---|---|
| Formátování jednoho nebo více objektů pomocí konvencí aktuální jazykové verze.Format one or more objects by using the conventions of the current culture. | S výjimkou přetížení, která obsahují provider parametr, zbývající Format přetížení zahrnují String parametr následovaný jedním nebo více parametrů objektu.Except for the overloads that include a provider parameter, the remaining Format overloads include a String parameter followed by one or more object parameters. Z tohoto důvodu nemusíte určit, které Format přetížení máte v úmyslu volat.Because of this, you don't have to determine which Format overload you intend to call. Kompilátor jazyka vybere odpovídající přetížení z v rámci přetížení, které nemají provider parametr, na základě vašeho seznamu argumentů.Your language compiler selects the appropriate overload from among the overloads that don't have a provider parameter, based on your argument list. Pokud má váš seznam argumentů například pět argumentů, volá kompilátor Format(String, Object[]) metodu.For example, if your argument list has five arguments, the compiler calls the Format(String, Object[]) method. |
| Formátování jednoho nebo více objektů pomocí konvencí konkrétní jazykové verze.Format one or more objects by using the conventions of a specific culture. | Každé Format přetížení, které začíná provider parametrem, následuje String parametr a jeden nebo více parametrů objektu.Each Format overload that begins with a provider parameter is followed by a String parameter and one or more object parameters. Z tohoto důvodu nemusíte určit, které konkrétní Format přetížení máte v úmyslu volat.Because of this, you don't have to determine which specific Format overload you intend to call. Kompilátor jazyka vybere odpovídající přetížení z v rámci přetížení, které mají provider parametr, na základě vašeho seznamu argumentů.Your language compiler selects the appropriate overload from among the overloads that have a provider parameter, based on your argument list. Pokud má váš seznam argumentů například pět argumentů, volá kompilátor Format(IFormatProvider, String, Object[]) metodu.For example, if your argument list has five arguments, the compiler calls the Format(IFormatProvider, String, Object[]) method. |
| Proveďte vlastní operaci formátování buď s ICustomFormatter implementací, nebo s IFormattable implementací.Perform a custom formatting operation either with an ICustomFormatter implementation or an IFormattable implementation. | Jakékoli čtyři přetížení s provider parametrem.Any of the four overloads with a provider parameter. Kompilátor vybere příslušné přetížení z přetížení, které má provider parametr, na základě vašeho seznamu argumentů.The compiler selects the appropriate overload from among the overloads that have a provider parameter, based on your argument list. |
Přehled metody FormatThe Format method in brief
Každé přetížení Format metody používá funkci složeného formátování k zahrnutí indexovaných zástupných symbolů založených na nule, nazývaných položky formátu, ve složeném formátovacím řetězci.Each overload of the Format method uses the composite formatting feature to include zero-based indexed placeholders, called format items, in a composite format string. V době běhu je každá položka formátu nahrazena řetězcovou reprezentací odpovídajícího argumentu v seznamu parametrů.At run time, each format item is replaced with the string representation of the corresponding argument in a parameter list. Pokud je hodnota argumentu null , položka formátu je nahrazena hodnotou String.Empty .If the value of the argument is null, the format item is replaced with String.Empty. Například následující volání Format(String, Object, Object, Object) metody obsahuje řetězec formátu se třemi položkami formátu,, {0} {1} a a {2} seznam argumentů se třemi položkami.For example, the following call to the Format(String, Object, Object, Object) method includes a format string with three format items, {0}, {1}, and {2}, and an argument list with three items.
using namespace System;
void main()
{
DateTime^ dat = gcnew DateTime(2012, 1, 17, 9, 30, 0);
String^ city = "Chicago";
int temp = -16;
String^ output = String::Format("At {0} in {1}, the temperature was {2} degrees.",
dat, city, temp);
Console::WriteLine(output);
}
// The example displays the following output:
// At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.
DateTime dat = new DateTime(2012, 1, 17, 9, 30, 0);
string city = "Chicago";
int temp = -16;
string output = String.Format("At {0} in {1}, the temperature was {2} degrees.",
dat, city, temp);
Console.WriteLine(output);
// The example displays output like the following:
// At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.
Dim dat As Date = #1/17/2012 9:30AM#
Dim city As String = "Chicago"
Dim temp As Integer = -16
Dim output As String = String.Format("At {0} in {1}, the temperature was {2} degrees.",
dat, city, temp)
Console.WriteLine(output)
' The example displays the following output:
' At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.
Položka formátuThe format item
Položka formátu má tuto syntaxi:A format item has this syntax:
{index[,alignment][:formatString]}
Hranaté závorky označují volitelné prvky.Brackets denote optional elements. Jsou vyžadovány levé a pravé složené závorky.The opening and closing braces are required. (Chcete-li do řetězce formátu zahrnout literálovou levou nebo pravou závorku, viz část uvozovací závorky v článku složeného formátování .)(To include a literal opening or closing brace in the format string, see the Escaping Braces section in the Composite Formatting article.)
Například položka formátu pro formátování hodnoty měny může vypadat takto:For example, a format item to format a currency value might appear like this:
String::Format("{0,-10:C}", (Decimal) 126347.89);
var value = String.Format("{0,-10:C}", 126347.89m);
Console.WriteLine(value);
String.Format("{0,-10:C}", 126347.89d)
Položka formátu má následující prvky:A format item has the following elements:
indexovacímindex
Index založený na nule argumentu, jehož řetězcová reprezentace má být na této pozici v řetězci vložena.The zero-based index of the argument whose string representation is to be included at this position in the string. Pokud je tento argument null , bude do této pozice v řetězci vložen prázdný řetězec.If this argument is null, an empty string will be included at this position in the string.
bodalignment
Nepovinný parametr.Optional. Celé číslo se znaménkem, které označuje celkovou délku pole, do něhož je vložen argument a zda je zarovnán vpravo (kladné celé číslo) nebo zarovnané vlevo (záporné celé číslo).A signed integer that indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer). Vynecháte-li Zarovnání, bude řetězcová reprezentace odpovídajícího argumentu vložena do pole bez mezer na začátku nebo na konci.If you omit alignment, the string representation of the corresponding argument is inserted in a field with no leading or trailing spaces.
Pokud je hodnota Zarovnání menší než délka argumentu, který se má vložit, Zarovnání se ignoruje a délka řetězcového vyjádření argumentu se používá jako šířka pole.If the value of alignment is less than the length of the argument to be inserted, alignment is ignored and the length of the string representation of the argument is used as the field width.
formatStringformatString
Nepovinný parametr.Optional. Řetězec, který určuje formát výsledného řetězce odpovídajícího argumentu.A string that specifies the format of the corresponding argument's result string. Vynecháte-li vlastnost formatString, je volána metoda bez parametrů odpovídající argumentu ToString pro vyprodukování řetězcové reprezentace.If you omit formatString, the corresponding argument's parameterless ToString method is called to produce its string representation. Zadáte-li vlastnost formatString, argument, na který odkazuje položka formátu, musí implementovat IFormattable rozhraní.If you specify formatString, the argument referenced by the format item must implement the IFormattable interface. Mezi typy, které podporují řetězce formátu, patří:Types that support format strings include:
Všechny typy integrálních a plovoucích bodů.All integral and floating-point types. (Viz Standardní číselné formátovací řetězce a řetězce vlastního číselného formátu.)(See Standard Numeric Format Strings and Custom Numeric Format Strings.)
DateTime a DateTimeOffset .DateTime and DateTimeOffset. (Viz Standardní řetězce formátu data a času a Vlastní řetězce formátu data a času.)(See Standard Date and Time Format Strings and Custom Date and Time Format Strings.)
Všechny typy výčtu.All enumeration types. (Viz řetězce formátu výčtu.)(See Enumeration Format Strings.)
TimeSpan hodnota.TimeSpan values. (Viz Standardní řetězce formátu TimeSpan a Vlastní řetězce formátu TimeSpan.)(See Standard TimeSpan Format Strings and Custom TimeSpan Format Strings.)
Identifikátory GUID.GUIDs. (Viz Guid.ToString(String) metoda.)(See the Guid.ToString(String) method.)
Upozorňujeme však, že libovolný vlastní typ může implementovat IFormattable nebo zvětšit implementaci stávajícího typu IFormattable .However, note that any custom type can implement IFormattable or extend an existing type's IFormattable implementation.
Následující příklad používá alignment formatString argumenty a k tvorbě formátovaného výstupu.The following example uses the alignment and formatString arguments to produce formatted output.
using namespace System;
void main()
{
// Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
array<Tuple<String^, DateTime, int, DateTime, int>^>^ cities = gcnew array<Tuple<String^, DateTime, int, DateTime, int>^>
{ gcnew Tuple<String^, DateTime, int, DateTime, int>("Los Angeles", DateTime(1940, 1, 1), 1504277,
DateTime(1950, 1, 1), 1970358),
gcnew Tuple<String^, DateTime, int, DateTime, int>("New York", DateTime(1940, 1, 1), 7454995,
DateTime(1950, 1, 1), 7891957),
gcnew Tuple<String^, DateTime, int, DateTime, int>("Chicago", DateTime(1940, 1, 1), 3396808,
DateTime(1950, 1, 1), 3620962),
gcnew Tuple<String^, DateTime, int, DateTime, int>("Detroit", DateTime(1940, 1, 1), 1623452,
DateTime(1950, 1, 1), 1849568) };
// Display header
String^ header = String::Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n",
"City", "Year", "Population", "Change (%)");
Console::WriteLine(header);
String^ output;
for each (Tuple<String^, DateTime, int, DateTime, int>^ city in cities) {
output = String::Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
city->Item1, city->Item2, city->Item3, city->Item4, city->Item5,
(city->Item5 - city->Item3)/ (double)city->Item3);
Console::WriteLine(output);
}
}
// The example displays the following output:
// City Year Population Year Population Change (%)
//
// Los Angeles 1940 1,504,277 1950 1,970,358 31.0 %
// New York 1940 7,454,995 1950 7,891,957 5.9 %
// Chicago 1940 3,396,808 1950 3,620,962 6.6 %
// Detroit 1940 1,623,452 1950 1,849,568 13.9 %
// Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
Tuple<string, DateTime, int, DateTime, int>[] cities =
{ Tuple.Create("Los Angeles", new DateTime(1940, 1, 1), 1504277,
new DateTime(1950, 1, 1), 1970358),
Tuple.Create("New York", new DateTime(1940, 1, 1), 7454995,
new DateTime(1950, 1, 1), 7891957),
Tuple.Create("Chicago", new DateTime(1940, 1, 1), 3396808,
new DateTime(1950, 1, 1), 3620962),
Tuple.Create("Detroit", new DateTime(1940, 1, 1), 1623452,
new DateTime(1950, 1, 1), 1849568) };
// Display header
var header = String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n",
"City", "Year", "Population", "Change (%)");
Console.WriteLine(header);
foreach (var city in cities) {
var output = String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
(city.Item5 - city.Item3)/ (double)city.Item3);
Console.WriteLine(output);
}
// The example displays the following output:
// City Year Population Year Population Change (%)
//
// Los Angeles 1940 1,504,277 1950 1,970,358 31.0 %
// New York 1940 7,454,995 1950 7,891,957 5.9 %
// Chicago 1940 3,396,808 1950 3,620,962 6.6 %
// Detroit 1940 1,623,452 1950 1,849,568 13.9 %
Module Example
Public Sub Main()
' Create array of 5-tuples with population data for three U.S. cities, 1940-1950.
Dim cities() = _
{ Tuple.Create("Los Angeles", #1/1/1940#, 1504277, #1/1/1950#, 1970358),
Tuple.Create("New York", #1/1/1940#, 7454995, #1/1/1950#, 7891957),
Tuple.Create("Chicago", #1/1/1940#, 3396808, #1/1/1950#, 3620962),
Tuple.Create("Detroit", #1/1/1940#, 1623452, #1/1/1950#, 1849568) }
' Display header
Dim header As String = String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}",
"City", "Year", "Population", "Change (%)")
Console.WriteLine(header)
Console.WriteLine()
For Each city In cities
Dim output = String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
(city.Item5 - city.Item3)/city.Item3)
Console.WriteLine(output)
Next
End Sub
End Module
' The example displays the following output:
' City Year Population Year Population Change (%)
'
' Los Angeles 1940 1,504,277 1950 1,970,358 31.0 %
' New York 1940 7,454,995 1950 7,891,957 5.9 %
' Chicago 1940 3,396,808 1950 3,620,962 6.6 %
' Detroit 1940 1,623,452 1950 1,849,568 13.9 %
Formátování argumentůHow arguments are formatted
Formátování položek se zpracovává postupně ze začátku řetězce.Format items are processed sequentially from the beginning of the string. Každá položka formátu má index, který odpovídá objektu v seznamu argumentů metody.Each format item has an index that corresponds to an object in the method's argument list. FormatMetoda načte argument a odvozuje jeho řetězcovou reprezentaci následujícím způsobem:The Format method retrieves the argument and derives its string representation as follows:
Pokud je argumentem
null, metoda vloží String.Empty do výsledného řetězce.If the argument isnull, the method inserts String.Empty into the result string. Nemusíte mít obavy se zpracováním NullReferenceException argumentů s hodnotou null.You don't have to be concerned with handling a NullReferenceException for null arguments.Pokud zavoláte Format(IFormatProvider, String, Object[]) přetížení a
providerIFormatProvider.GetFormat implementace objektu vrátí implementaci, která není null ICustomFormatter , argument se předává do své ICustomFormatter.Format(String, Object, IFormatProvider) metody.If you call the Format(IFormatProvider, String, Object[]) overload and theproviderobject's IFormatProvider.GetFormat implementation returns a non-null ICustomFormatter implementation, the argument is passed to its ICustomFormatter.Format(String, Object, IFormatProvider) method. Pokud položka formátu obsahuje argument formatString , je předána jako první argument metody.If the format item includes a formatString argument, it is passed as the first argument to the method. Pokud ICustomFormatter je implementace k dispozici a vytváří řetězec, který není null, tento řetězec je vrácen jako řetězcové vyjádření argumentu. v opačném případě se provede další krok.If the ICustomFormatter implementation is available and produces a non-null string, that string is returned as the string representation of the argument; otherwise, the next step executes.Pokud argument implementuje IFormattable rozhraní, IFormattable.ToString je volána jeho implementace.If the argument implements the IFormattable interface, its IFormattable.ToString implementation is called.
Je volána metoda bez parametrů argumentu
ToString, která buď Přepisuje nebo dědí z implementace základní třídy.The argument's parameterlessToStringmethod, which either overrides or inherits from a base class implementation, is called.
Příklad, který zachycuje volání ICustomFormatter.Format metody a umožňuje zjistit, jaké informace Format Metoda předává metodě formátování pro každou položku formátu ve složeném formátovacím řetězci, viz Příklad: poskytovatel zachycení a formátovací modul římských číslic.For an example that intercepts calls to the ICustomFormatter.Format method and allows you to see what information the Format method passes to a formatting method for each format item in a composite format string, see Example: An intercept provider and Roman numeral formatter.
Další informace naleznete v části pořadí zpracování v článku složeného formátování .For more information, see the Processing Order section in the Composite Formatting article.
Položky formátu, které mají stejný indexFormat items that have the same index
FormatMetoda vyvolá výjimku, FormatException Pokud je index položky indexu větší nebo roven počtu argumentů v seznamu argumentů.The Format method throws a FormatException exception if the index of an index item is greater than or equal to the number of arguments in the argument list. Může však format obsahovat více položek formátu, než jsou argumenty, pokud více položek formátu má stejný index.However, format can include more format items than there are arguments, as long as multiple format items have the same index. V volání Format(String, Object) metody v následujícím příkladu má seznam argumentů jeden argument, ale formátovací řetězec obsahuje dvě položky formátu: jedna zobrazuje desítkovou hodnotu čísla a druhá zobrazí svou hexadecimální hodnotu.In the call to the Format(String, Object) method in following example, the argument list has a single argument, but the format string includes two format items: one displays the decimal value of a number, and the other displays its hexadecimal value.
short[] values= { Int16.MinValue, -27, 0, 1042, Int16.MaxValue };
Console.WriteLine("{0,10} {1,10}\n", "Decimal", "Hex");
foreach (short value in values)
{
string formatString = String.Format("{0,10:G}: {0,10:X}", value);
Console.WriteLine(formatString);
}
// The example displays the following output:
// Decimal Hex
//
// -32768: 8000
// -27: FFE5
// 0: 0
// 1042: 412
// 32767: 7FFF
Module Example
Public Sub Main()
Dim values() As Short = { Int16.MinValue, -27, 0, 1042, Int16.MaxValue }
Console.WriteLine("{0,10} {1,10}", "Decimal", "Hex")
Console.WriteLine()
For Each value As Short In values
Dim formatString As String = String.Format("{0,10:G}: {0,10:X}", value)
Console.WriteLine(formatString)
Next
End Sub
End Module
' The example displays the following output:
' Decimal Hex
'
' -32768: 8000
' -27: FFE5
' 0: 0
' 1042: 412
' 32767: 7FFF
Formát a jazyková verzeFormat and culture
Obecně jsou objekty v seznamu argumentů převedeny na své řetězcové reprezentace pomocí konvencí aktuální jazykové verze, která je vrácena CultureInfo.CurrentCulture vlastností.Generally, objects in the argument list are converted to their string representations by using the conventions of the current culture, which is returned by the CultureInfo.CurrentCulture property. Toto chování lze řídit voláním jednoho z přetížení Format , které obsahují provider parametr.You can control this behavior by calling one of the overloads of Format that includes a provider parameter. providerParametr je IFormatProvider implementace, která poskytuje vlastní informace o formátování a specifické jazykové verze, které se používají pro střední proces formátování.The provider parameter is an IFormatProvider implementation that supplies custom and culture-specific formatting information that is used to moderate the formatting process.
IFormatProviderRozhraní má jediný člen, GetFormat , který je zodpovědný za vrácení objektu, který poskytuje informace o formátování.The IFormatProvider interface has a single member, GetFormat, which is responsible for returning the object that provides formatting information. Rozhraní .NET má tři IFormatProvider implementace, které poskytují formátování specifické pro jazykovou verzi:.NET has three IFormatProvider implementations that provide culture-specific formatting:
CultureInfo.CultureInfo. Jeho GetFormat Metoda vrátí objekt specifický pro jazykovou verzi NumberFormatInfo pro formátování číselných hodnot a objekt specifický pro jazykovou verzi DateTimeFormatInfo pro formátování hodnot data a času.Its GetFormat method returns a culture-specific NumberFormatInfo object for formatting numeric values and a culture-specific DateTimeFormatInfo object for formatting date and time values.
DateTimeFormatInfo, který se používá pro formátování hodnot data a času specifických pro jazykovou verzi.DateTimeFormatInfo, which is used for culture-specific formatting of date and time values. Jeho GetFormat Metoda vrátí sám sebe.Its GetFormat method returns itself.
NumberFormatInfo, který se používá pro formátování číselných hodnot specifických pro jazykovou verzi.NumberFormatInfo, which is used for culture-specific formatting of numeric values. Jeho GetFormat vlastnost vrací sám sebe.Its GetFormat property returns itself.
Vlastní operace formátováníCustom formatting operations
Můžete také volat kterékoli přetížení Format metody, která má provider parametr typu IFormatProvider k provádění operací vlastního formátování.You can also call the any of the overloads of the Format method that have a provider parameter of type IFormatProvider to perform custom formatting operations. Můžete například formátovat celé číslo jako identifikační číslo nebo jako telefonní číslo.For example, you could format an integer as an identification number or as a telephone number. Chcete-li provést vlastní formátování, váš provider argument musí implementovat IFormatProvider ICustomFormatter rozhraní a.To perform custom formatting, your provider argument must implement both the IFormatProvider and ICustomFormatter interfaces. Když Format Metoda předává ICustomFormatter implementaci jako provider argument, Format metoda volá svou IFormatProvider.GetFormat implementaci a požaduje objekt typu ICustomFormatter .When the Format method is passed an ICustomFormatter implementation as the provider argument, the Format method calls its IFormatProvider.GetFormat implementation and requests an object of type ICustomFormatter. Pak zavolá metodu vráceného ICustomFormatter objektu Format pro naformátování všech položek formátu v složeném řetězci, který je předaný do něj.It then calls the returned ICustomFormatter object's Format method to format each format item in the composite string passed to it.
Další informace o poskytování vlastních řešení formátování naleznete v tématu How to: Define and use Custom Numeric Format Providers and ICustomFormatter .For more information about providing custom formatting solutions, see How to: Define and Use Custom Numeric Format Providers and ICustomFormatter. Příklad, který převádí celá čísla na formátovaná vlastní čísla, naleznete v tématu Příklad: vlastní operace formátování.For an example that converts integers to formatted custom numbers, see Example: A custom formatting operation. Příklad, který převede nepodepsané bajty na římské číslice, najdete v tématu Příklad: poskytovatel zachycení a formátovací modul římských číslic.For an example that converts unsigned bytes to Roman numerals, see Example: An intercept provider and Roman numeral formatter.
Příklad: vlastní operace formátováníExample: A custom formatting operation
Tento příklad definuje poskytovatele formátu, který formátuje hodnotu typu Integer jako číslo účtu zákazníka ve formátu x-xxxxx-xx.This example defines a format provider that formats an integer value as a customer account number in the form x-xxxxx-xx.
using namespace System;
ref class CustomerFormatter : IFormatProvider, ICustomFormatter
{
public:
virtual Object^ GetFormat(Type^ formatType)
{
if (formatType == ICustomFormatter::typeid)
return this;
else
return nullptr;
}
virtual String^ Format(String^ format,
Object^ arg,
IFormatProvider^ formatProvider)
{
if (! this->Equals(formatProvider))
{
return nullptr;
}
else
{
if (String::IsNullOrEmpty(format))
format = "G";
String^ customerString = arg->ToString();
if (customerString->Length < 8)
customerString = customerString->PadLeft(8, '0');
format = format->ToUpper();
if (format == L"G")
return customerString->Substring(0, 1) + "-" +
customerString->Substring(1, 5) + "-" +
customerString->Substring(6);
else if (format == L"S")
return customerString->Substring(0, 1) + "/" +
customerString->Substring(1, 5) + "/" +
customerString->Substring(6);
else if (format == L"P")
return customerString->Substring(0, 1) + "." +
customerString->Substring(1, 5) + "." +
customerString->Substring(6);
else
throw gcnew FormatException(
String::Format("The '{0}' format specifier is not supported.", format));
}
}
};
void main()
{
int acctNumber = 79203159;
Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0}", acctNumber));
Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:G}", acctNumber));
Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:S}", acctNumber));
Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:P}", acctNumber));
try {
Console::WriteLine(String::Format(gcnew CustomerFormatter, "{0:X}", acctNumber));
}
catch (FormatException^ e) {
Console::WriteLine(e->Message);
}
}
// The example displays the following output:
// 7-92031-59
// 7-92031-59
// 7/92031/59
// 7.92031.59
// The 'X' format specifier is not supported.
using System;
public class TestFormatter
{
public static void Main()
{
int acctNumber = 79203159;
Console.WriteLine(String.Format(new CustomerFormatter(), "{0}", acctNumber));
Console.WriteLine(String.Format(new CustomerFormatter(), "{0:G}", acctNumber));
Console.WriteLine(String.Format(new CustomerFormatter(), "{0:S}", acctNumber));
Console.WriteLine(String.Format(new CustomerFormatter(), "{0:P}", acctNumber));
try {
Console.WriteLine(String.Format(new CustomerFormatter(), "{0:X}", acctNumber));
}
catch (FormatException e) {
Console.WriteLine(e.Message);
}
}
}
public class CustomerFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(string format,
object arg,
IFormatProvider formatProvider)
{
if (! this.Equals(formatProvider))
{
return null;
}
else
{
if (String.IsNullOrEmpty(format))
format = "G";
string customerString = arg.ToString();
if (customerString.Length < 8)
customerString = customerString.PadLeft(8, '0');
format = format.ToUpper();
switch (format)
{
case "G":
return customerString.Substring(0, 1) + "-" +
customerString.Substring(1, 5) + "-" +
customerString.Substring(6);
case "S":
return customerString.Substring(0, 1) + "/" +
customerString.Substring(1, 5) + "/" +
customerString.Substring(6);
case "P":
return customerString.Substring(0, 1) + "." +
customerString.Substring(1, 5) + "." +
customerString.Substring(6);
default:
throw new FormatException(
String.Format("The '{0}' format specifier is not supported.", format));
}
}
}
}
// The example displays the following output:
// 7-92031-59
// 7-92031-59
// 7/92031/59
// 7.92031.59
// The 'X' format specifier is not supported.
Module TestFormatter
Public Sub Main()
Dim acctNumber As Integer = 79203159
Console.WriteLine(String.Format(New CustomerFormatter, "{0}", acctNumber))
Console.WriteLine(String.Format(New CustomerFormatter, "{0:G}", acctNumber))
Console.WriteLine(String.Format(New CustomerFormatter, "{0:S}", acctNumber))
Console.WriteLine(String.Format(New CustomerFormatter, "{0:P}", acctNumber))
Try
Console.WriteLine(String.Format(New CustomerFormatter, "{0:X}", acctNumber))
Catch e As FormatException
Console.WriteLine(e.Message)
End Try
End Sub
End Module
Public Class CustomerFormatter : Implements IFormatProvider, ICustomFormatter
Public Function GetFormat(type As Type) As Object _
Implements IFormatProvider.GetFormat
If type Is GetType(ICustomFormatter) Then
Return Me
Else
Return Nothing
End If
End Function
Public Function Format(fmt As String, _
arg As Object, _
formatProvider As IFormatProvider) As String _
Implements ICustomFormatter.Format
If Not Me.Equals(formatProvider) Then
Return Nothing
Else
If String.IsNullOrEmpty(fmt) Then fmt = "G"
Dim customerString As String = arg.ToString()
if customerString.Length < 8 Then _
customerString = customerString.PadLeft(8, "0"c)
Select Case fmt
Case "G"
Return customerString.Substring(0, 1) & "-" & _
customerString.Substring(1, 5) & "-" & _
customerString.Substring(6)
Case "S"
Return customerString.Substring(0, 1) & "/" & _
customerString.Substring(1, 5) & "/" & _
customerString.Substring(6)
Case "P"
Return customerString.Substring(0, 1) & "." & _
customerString.Substring(1, 5) & "." & _
customerString.Substring(6)
Case Else
Throw New FormatException( _
String.Format("The '{0}' format specifier is not supported.", fmt))
End Select
End If
End Function
End Class
' The example displays the following output:
' 7-92031-59
' 7-92031-59
' 7/92031/59
' 7.92031.59
' The 'X' format specifier is not supported.
Příklad: Zprostředkovatel zachycení a formátovací modul římské čísliceExample: An intercept provider and Roman numeral formatter
Tento příklad definuje poskytovatele vlastního formátu, který implementuje ICustomFormatter rozhraní a, IFormatProvider aby provede dvě věci:This example defines a custom format provider that implements the ICustomFormatter and IFormatProvider interfaces to do two things:
Zobrazuje parametry předané jeho ICustomFormatter.Format implementaci.It displays the parameters passed to its ICustomFormatter.Format implementation. Díky tomu můžeme zjistit, jaké parametry Format(IFormatProvider, String, Object[]) Metoda předává implementaci vlastního formátování pro každý objekt, který se pokouší formátovat.This enables us to see what parameters the Format(IFormatProvider, String, Object[]) method is passing to the custom formatting implementation for each object that it tries to format. To může být užitečné při ladění aplikace.This can be useful when you're debugging your application.
Pokud objekt, který má být formátován, je hodnota bajt bez znaménka, který má být formátován pomocí řetězce standardního formátu "R", vlastní formátovací modul formátuje číselnou hodnotu jako římské číslo.If the object to be formatted is an unsigned byte value that is to be formatted by using the "R" standard format string, the custom formatter formats the numeric value as a Roman numeral.
using namespace System;
using namespace System::Globalization;
ref class InterceptProvider : IFormatProvider, ICustomFormatter
{
public:
virtual Object^ GetFormat(Type^ formatType)
{
if (formatType == ICustomFormatter::typeid)
return this;
else
return nullptr;
}
virtual String^ Format(String^ format, Object^ obj, IFormatProvider^ provider)
{
// Display information about method call.
String^ formatString = format != nullptr ? format : "<null>";
Console::WriteLine("Provider: {0}, Object: {1}, Format String: {2}",
provider, obj != nullptr ? obj : "<null>", formatString);
if (obj == nullptr) return String::Empty;
// If this is a byte and the "R" format string, format it with Roman numerals.
if (obj->GetType() == Byte::typeid && formatString->ToUpper()->Equals("R")) {
Byte value = (Byte) obj;
int remainder;
int result;
String^ returnString = String::Empty;
// Get the hundreds digit(s)
result = Math::DivRem(value, 100, remainder);
if (result > 0)
returnString = gcnew String('C', result);
value = (Byte) remainder;
// Get the 50s digit
result = Math::DivRem(value, 50, remainder);
if (result == 1)
returnString += "L";
value = (Byte) remainder;
// Get the tens digit.
result = Math::DivRem(value, 10, remainder);
if (result > 0)
returnString += gcnew String('X', result);
value = (Byte) remainder;
// Get the fives digit.
result = Math::DivRem(value, 5, remainder);
if (result > 0)
returnString += "V";
value = (Byte) remainder;
// Add the ones digit.
if (remainder > 0)
returnString += gcnew String('I', remainder);
// Check whether we have too many X characters.
int pos = returnString->IndexOf("XXXX");
if (pos >= 0) {
int xPos = returnString->IndexOf("L");
if ((xPos >= 0) & (xPos == pos - 1))
returnString = returnString->Replace("LXXXX", "XC");
else
returnString = returnString->Replace("XXXX", "XL");
}
// Check whether we have too many I characters
pos = returnString->IndexOf("IIII");
if (pos >= 0)
if (returnString->IndexOf("V") >= 0)
returnString = returnString->Replace("VIIII", "IX");
else
returnString = returnString->Replace("IIII", "IV");
return returnString;
}
// Use default for all other formatting.
if (obj->GetType() == IFormattable::typeid)
return ((IFormattable^) obj)->ToString(format, CultureInfo::CurrentCulture);
else
return obj->ToString();
}
};
void main()
{
int n = 10;
double value = 16.935;
DateTime day = DateTime::Now;
InterceptProvider^ provider = gcnew InterceptProvider();
Console::WriteLine(String::Format(provider, "{0:N0}: {1:C2} on {2:d}\n", n, value, day));
Console::WriteLine(String::Format(provider, "{0}: {1:F}\n", "Today: ",
(DayOfWeek) DateTime::Now.DayOfWeek));
Console::WriteLine(String::Format(provider, "{0:X}, {1}, {2}\n",
(Byte) 2, (Byte) 12, (Byte) 199));
Console::WriteLine(String::Format(provider, "{0:R}, {1:R}, {2:R}\n",
(Byte) 2, (Byte) 12, (Byte) 199));
}
// The example displays the following output:
// Provider: InterceptProvider, Object: 10, Format String: N0
// Provider: InterceptProvider, Object: 16.935, Format String: C2
// Provider: InterceptProvider, Object: 1/31/2013 6:10:28 PM, Format String: d
// 10: $16.94 on 1/31/2013
//
// Provider: InterceptProvider, Object: Today: , Format String: <null>
// Provider: InterceptProvider, Object: Thursday, Format String: F
// Today: : Thursday
//
// Provider: InterceptProvider, Object: 2, Format String: X
// Provider: InterceptProvider, Object: 12, Format String: <null>
// Provider: InterceptProvider, Object: 199, Format String: <null>
// 2, 12, 199
//
// Provider: InterceptProvider, Object: 2, Format String: R
// Provider: InterceptProvider, Object: 12, Format String: R
// Provider: InterceptProvider, Object: 199, Format String: R
// II, XII, CXCIX
using System;
using System.Globalization;
public class InterceptProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(String format, Object obj, IFormatProvider provider)
{
// Display information about method call.
string formatString = format ?? "<null>";
Console.WriteLine("Provider: {0}, Object: {1}, Format String: {2}",
provider.GetType().Name, obj ?? "<null>", formatString);
if (obj == null) return String.Empty;
// If this is a byte and the "R" format string, format it with Roman numerals.
if (obj is Byte && formatString.ToUpper().Equals("R")) {
Byte value = (Byte) obj;
int remainder;
int result;
String returnString = String.Empty;
// Get the hundreds digit(s)
result = Math.DivRem(value, 100, out remainder);
if (result > 0)
returnString = new String('C', result);
value = (Byte) remainder;
// Get the 50s digit
result = Math.DivRem(value, 50, out remainder);
if (result == 1)
returnString += "L";
value = (Byte) remainder;
// Get the tens digit.
result = Math.DivRem(value, 10, out remainder);
if (result > 0)
returnString += new String('X', result);
value = (Byte) remainder;
// Get the fives digit.
result = Math.DivRem(value, 5, out remainder);
if (result > 0)
returnString += "V";
value = (Byte) remainder;
// Add the ones digit.
if (remainder > 0)
returnString += new String('I', remainder);
// Check whether we have too many X characters.
int pos = returnString.IndexOf("XXXX");
if (pos >= 0) {
int xPos = returnString.IndexOf("L");
if (xPos >= 0 & xPos == pos - 1)
returnString = returnString.Replace("LXXXX", "XC");
else
returnString = returnString.Replace("XXXX", "XL");
}
// Check whether we have too many I characters
pos = returnString.IndexOf("IIII");
if (pos >= 0)
if (returnString.IndexOf("V") >= 0)
returnString = returnString.Replace("VIIII", "IX");
else
returnString = returnString.Replace("IIII", "IV");
return returnString;
}
// Use default for all other formatting.
if (obj is IFormattable)
return ((IFormattable) obj).ToString(format, CultureInfo.CurrentCulture);
else
return obj.ToString();
}
}
public class Example
{
public static void Main()
{
int n = 10;
double value = 16.935;
DateTime day = DateTime.Now;
InterceptProvider provider = new InterceptProvider();
Console.WriteLine(String.Format(provider, "{0:N0}: {1:C2} on {2:d}\n", n, value, day));
Console.WriteLine(String.Format(provider, "{0}: {1:F}\n", "Today: ",
(DayOfWeek) DateTime.Now.DayOfWeek));
Console.WriteLine(String.Format(provider, "{0:X}, {1}, {2}\n",
(Byte) 2, (Byte) 12, (Byte) 199));
Console.WriteLine(String.Format(provider, "{0:R}, {1:R}, {2:R}\n",
(Byte) 2, (Byte) 12, (Byte) 199));
}
}
// The example displays the following output:
// Provider: InterceptProvider, Object: 10, Format String: N0
// Provider: InterceptProvider, Object: 16.935, Format String: C2
// Provider: InterceptProvider, Object: 1/31/2013 6:10:28 PM, Format String: d
// 10: $16.94 on 1/31/2013
//
// Provider: InterceptProvider, Object: Today: , Format String: <null>
// Provider: InterceptProvider, Object: Thursday, Format String: F
// Today: : Thursday
//
// Provider: InterceptProvider, Object: 2, Format String: X
// Provider: InterceptProvider, Object: 12, Format String: <null>
// Provider: InterceptProvider, Object: 199, Format String: <null>
// 2, 12, 199
//
// Provider: InterceptProvider, Object: 2, Format String: R
// Provider: InterceptProvider, Object: 12, Format String: R
// Provider: InterceptProvider, Object: 199, Format String: R
// II, XII, CXCIX
Imports System.Globalization
Public Class InterceptProvider : Implements IFormatProvider, ICustomFormatter
Public Function GetFormat(formatType As Type) As Object _
Implements IFormatProvider.GetFormat
If formatType Is GetType(ICustomFormatter) Then
Return Me
Else
Return Nothing
End If
End Function
Public Function Format(fmt As String, obj As Object, provider As IFormatProvider) As String _
Implements ICustomFormatter.Format
Dim formatString As String = If(fmt IsNot Nothing, fmt, "<null>")
Console.WriteLine("Provider: {0}, Object: {1}, Format String: {2}",
provider, If(obj IsNot Nothing, obj, "<null>"), formatString)
If obj Is Nothing Then Return String.Empty
' If this is a byte and the "R" format string, format it with Roman numerals.
If TypeOf(obj) Is Byte AndAlso formatString.ToUpper.Equals("R") Then
Dim value As Byte = CByte(obj)
Dim remainder As Integer
Dim result As Integer
Dim returnString As String = String.Empty
' Get the hundreds digit(s)
result = Math.DivRem(value, 100, remainder)
If result > 0 Then returnString = New String("C"c, result)
value = CByte(remainder)
' Get the 50s digit
result = Math.DivRem(value, 50, remainder)
If result = 1 Then returnString += "L"
value = CByte(remainder)
' Get the tens digit.
result = Math.DivRem(value, 10, remainder)
If result > 0 Then returnString += New String("X"c, result)
value = CByte(remainder)
' Get the fives digit.
result = Math.DivRem(value, 5, remainder)
If result > 0 Then returnString += "V"
value = CByte(remainder)
' Add the ones digit.
If remainder > 0 Then returnString += New String("I"c, remainder)
' Check whether we have too many X characters.
Dim pos As Integer = returnString.IndexOf("XXXX")
If pos >= 0 Then
Dim xPos As Integer = returnString.IndexOf("L")
If xPos >= 0 And xPos = pos - 1 Then
returnString = returnString.Replace("LXXXX", "XC")
Else
returnString = returnString.Replace("XXXX", "XL")
End If
End If
' Check whether we have too many I characters
pos = returnString.IndexOf("IIII")
If pos >= 0 Then
If returnString.IndexOf("V") >= 0 Then
returnString = returnString.Replace("VIIII", "IX")
Else
returnString = returnString.Replace("IIII", "IV")
End If
End If
Return returnString
End If
' Use default for all other formatting.
If obj Is GetType(IFormattable)
Return CType(obj, IFormattable).ToString(fmt, CultureInfo.CurrentCulture)
Else
Return obj.ToString()
End If
End Function
End Class
Module Example
Public Sub Main()
Dim n As Integer = 10
Dim value As Double = 16.935
Dim day As DateTime = Date.Now
Dim provider As New InterceptProvider()
Console.WriteLine(String.Format(provider, "{0:N0}: {1:C2} on {2:d}", n, value, day))
Console.WriteLine()
Console.WriteLine(String.Format(provider, "{0}: {1:F}", "Today",
CType(Date.Now.DayOfWeek, DayOfWeek)))
Console.WriteLine()
Console.WriteLine(String.Format(provider, "{0:X}, {1}, {2}\n",
CByte(2), CByte(12), CByte(199)))
Console.WriteLine()
Console.WriteLine(String.Format(provider, "{0:R}, {1:R}, {2:R}",
CByte(2), CByte(12), CByte(199)))
End Sub
End Module
' The example displays the following output:
' Provider: InterceptProvider, Object: 10, Format String: N0
' Provider: InterceptProvider, Object: 16.935, Format String: C2
' Provider: InterceptProvider, Object: 1/31/2013 6:10:28 PM, Format String: d
' 10: $16.94 on 1/31/2013
'
' Provider: InterceptProvider, Object: Today: , Format String: <null>
' Provider: InterceptProvider, Object: Thursday, Format String: F
' Today: : Thursday
'
' Provider: InterceptProvider, Object: 2, Format String: X
' Provider: InterceptProvider, Object: 12, Format String: <null>
' Provider: InterceptProvider, Object: 199, Format String: <null>
' 2, 12, 199
'
' Provider: InterceptProvider, Object: 2, Format String: R
' Provider: InterceptProvider, Object: 12, Format String: R
' Provider: InterceptProvider, Object: 199, Format String: R
' II, XII, CXCIX
String. Format Q & AString.Format Q & A
Proč doporučujeme použít řetězcovou interpolaci v volání String.Format metody?Why do you recommend string interpolation over calls to the String.Format method?
Interpolace řetězců je:String interpolation is:
Flexibilnější.More flexible. Dá se použít v jakémkoli řetězci bez nutnosti volat metodu, která podporuje složené formátování.It can be used in any string without requiring a call to a method that supports composite formatting. V opačném případě je nutné zavolat Format metodu nebo jinou metodu, která podporuje složené formátování, například Console.WriteLine nebo StringBuilder.AppendFormat .Otherwise, you have to call the Format method or another method that supports composite formatting, such as Console.WriteLine or StringBuilder.AppendFormat.
Čitelnější.More readable. Vzhledem k tomu, že výraz pro vložení do řetězce se zobrazí v interpolované výrazu, nikoli v seznamu argumentů, interpolované řetězce jsou mnohem snazší Code a čteny.Because the expression to insert into a string appears in the interpolated expression rather than in a argument list, interpolated strings are far easier to code and to read. Z důvodu jejich lepší čitelnosti mohou interpolované řetězce nahradit nejen volání složených formátovacích metod, ale lze je také použít v operacích zřetězení řetězců k tvorbě výstižnější a srozumitelného kódu.Because of their greater readability, interpolated strings can replace not only calls to composite format methods, but they can also be used in string concatenation operations to produce more concise, clearer code.
Porovnání následujících dvou příkladů kódu ukazuje nadřazenou hodnotu interpolované řetězce přes zřetězení řetězců a volání metod složeného formátování.A comparison of the following two code examples illustrates the superiority of interpolated strings over string concatenation and calls to composite formatting methods. Použití operací zřetězení více řetězců v následujícím příkladu vytvoří podrobný a kód, který je špatně čitelný.The use of multiple string concatenation operations in the following example produces verbose and hard-to-read code.
string[] names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" };
string output = names[0] + ", " + names[1] + ", " + names[2] + ", " +
names[3] + ", " + names[4] + ", " + names[5] + ", " +
names[6];
output += "\n";
var date = DateTime.Now;
output += String.Format("It is {0:t} on {0:d}. The day of the week is {1}.",
date, date.DayOfWeek);
Console.WriteLine(output);
// The example displays the following output:
// Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
// It is 10:29 AM on 1/8/2018. The day of the week is Monday.
Module Example
Public Sub Main()
Dim names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" }
Dim output = names(0) + ", " + names(1) + ", " + names(2) + ", " +
names(3) + ", " + names(4) + ", " + names(5) + ", " +
names(6)
output += vbCrLf
Dim dat = DateTime.Now
output += String.Format("It is {0:t} on {0:d}. The day of the week is {1}.",
dat, dat.DayOfWeek)
Console.WriteLine(output)
End Sub
End Module
' The example displays the following output:
' Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
' It is 10:29 AM on 1/8/2018. The day of the week is Monday.
Naopak použití interpolované řetězce v následujícím příkladu produkuje mnohem jasný, výstižný kód než příkaz zřetězení řetězce a volání Format metody v předchozím příkladu.In contrast, the use of interpolated strings in the following example produce much clearer, more concise code than the string concatenation statement and the call to the Format method in the previous example.
string[] names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" };
string output = $"{names[0]}, {names[1]}, {names[2]}, {names[3]}, {names[4]}, " +
$"{names[5]}, {names[6]}";
var date = DateTime.Now;
output += $"\nIt is {date:t} on {date:d}. The day of the week is {date.DayOfWeek}.";
Console.WriteLine(output);
// The example displays the following output:
// Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
// It is 10:29 AM on 1/8/2018. The day of the week is Monday.
Module Example
Public Sub Main()
Dim names = { "Balto", "Vanya", "Dakota", "Samuel", "Koani", "Yiska", "Yuma" }
Dim output = $"{names(0)}, {names(1)}, {names(2)}, {names(3)}, {names(4)}, " +
$"{names(5)}, {names(6)}"
Dim dat = DateTime.Now
output += $"{vbCrLf}It is {dat:t} on {dat:d}. The day of the week is {dat.DayOfWeek}."
Console.WriteLine(output)
End Sub
End Module
' The example displays the following output:
' Balto, Vanya, Dakota, Samuel, Koani, Yiska, Yuma
' It is 10:29 AM on 1/8/2018. The day of the week is Monday.
Kde najdu seznam předdefinovaných formátovacích řetězců, které lze použít s položkami formátu?Where can I find a list of the predefined format strings that can be used with format items?
Pro všechny typy integrálních a plovoucích bodů si přečtěte téma Standardní číselné formátovací řetězce a vlastní číselné formátovací řetězce.For all integral and floating-point types, see Standard Numeric Format Strings and Custom Numeric Format Strings.
Hodnoty data a času naleznete v tématu Standardní řetězce formátu data a času a Vlastní řetězce formátu data a času.For date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.
Hodnoty výčtu naleznete v tématu řetězce formátu výčtu.For enumeration values, see Enumeration Format Strings.
TimeSpanHodnoty naleznete v tématu Standardní řetězce formátu TimeSpan a Vlastní řetězce formátu TimeSpan.For TimeSpan values, see Standard TimeSpan Format Strings and Custom TimeSpan Format Strings.
Hodnoty naleznete v Guid části poznámky na Guid.ToString(String) referenční stránce.For Guid values, see the Remarks section of the Guid.ToString(String) reference page.
Návody řízení zarovnání výsledných řetězců, které nahrazují položky formátu?How do I control the alignment of the result strings that replace format items?
Obecná syntaxe položky formátu je:The general syntax of a format item is:
{index[,alignment][: formatString]}
kde Zarovnání je celé číslo se znaménkem, které definuje šířku pole.where alignment is a signed integer that defines the field width. Pokud je tato hodnota záporná, text v poli je zarovnán vlevo.If this value is negative, text in the field is left-aligned. Pokud je kladné, text je zarovnán vpravo.If it is positive, text is right-aligned.
Návody řídit počet číslic za oddělovačem desetinných míst?How do I control the number of digits after the decimal separator?
Všechny Standardní číselné formátovací řetězce s výjimkou "D" (který se používá pouze s celými čísly), "G", "R" a "X" umožňují specifikátor přesnosti, který definuje počet desítkových číslic ve výsledném řetězci.All standard numeric format strings except "D" (which is used with integers only), "G", "R", and "X" allow a precision specifier that defines the number of decimal digits in the result string. Následující příklad používá standardní číselné formátovací řetězce pro řízení počtu desítkových číslic ve výsledném řetězci.The following example uses standard numeric format strings to control the number of decimal digits in the result string.
object[] values = { 1603, 1794.68235, 15436.14 };
string result;
foreach (var value in values) {
result = String.Format("{0,12:C2} {0,12:E3} {0,12:F4} {0,12:N3} {1,12:P2}\n",
Convert.ToDouble(value), Convert.ToDouble(value) / 10000);
Console.WriteLine(result);
}
// The example displays output like the following:
// $1,603.00 1.603E+003 1603.0000 1,603.000 16.03 %
//
// $1,794.68 1.795E+003 1794.6824 1,794.682 17.95 %
//
// $15,436.14 1.544E+004 15436.1400 15,436.140 154.36 %
Module Example
Public Sub Main()
Dim values() As Object = { 1603, 1794.68235, 15436.14 }
Dim result As String
For Each value In values
result = String.Format("{0,12:C2} {0,12:E3} {0,12:F4} {0,12:N3} {1,12:P2}",
value, CDbl(value) / 10000)
Console.WriteLine(result)
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' $1,603.00 1.603E+003 1603.0000 1,603.000 16.03 %
'
' $1,794.68 1.795E+003 1794.6824 1,794.682 17.95 %
'
' $15,436.14 1.544E+004 15436.1400 15,436.140 154.36 %
Pokud používáte vlastní řetězec číselného formátu, použijte specifikátor formátu "0" pro řízení počtu desítkových číslic ve výsledném řetězci, jak ukazuje následující příklad.If you're using a custom numeric format string, use the "0" format specifier to control the number of decimal digits in the result string, as the following example shows.
decimal value = 16309.5436m;
string result = String.Format("{0,12:#.00000} {0,12:0,000.00} {0,12:000.00#}",
value);
Console.WriteLine(result);
// The example displays the following output:
// 16309.54360 16,309.54 16309.544
Module Example
Public Sub Main()
Dim value As Decimal = 16309.5436d
Dim result As String = String.Format("{0,12:#.00000} {0,12:0,000.00} {0,12:000.00#}",
value)
Console.WriteLine(result)
End Sub
End Module
' The example displays the following output:
' 16309.54360 16,309.54 16309.544
Návody řídit počet integrálních číslic?How do I control the number of integral digits?
Ve výchozím nastavení se v operacích formátování zobrazují pouze nenulové celočíselné číslice.By default, formatting operations only display non-zero integral digits. Pokud formátujete celá čísla, můžete použít specifikátor přesnosti s řetězcem standardního formátu "D" a "X" pro řízení počtu číslic.If you are formatting integers, you can use a precision specifier with the "D" and "X" standard format strings to control the number of digits.
int value = 1326;
string result = String.Format("{0,10:D6} {0,10:X8}", value);
Console.WriteLine(result);
// The example displays the following output:
// 001326 0000052E
Module Example
Public Sub Main()
Dim value As Integer = 1326
Dim result As String = String.Format("{0,10:D6} {0,10:X8}", value)
Console.WriteLine(result)
End Sub
End Module
' The example displays the following output:
' 001326 0000052E
Můžete doplnit celé číslo nebo číslo s plovoucí desetinnou čárkou s počátečními nulami pro vytvoření výsledného řetězce se zadaným počtem integrálních číslic pomocí specifikátoru vlastního číselného formátu"0", jak ukazuje následující příklad.You can pad an integer or floating-point number with leading zeros to produce a result string with a specified number of integral digits by using the "0" custom numeric format specifier, as the following example shows.
int value = 16342;
string result = String.Format("{0,18:00000000} {0,18:00000000.000} {0,18:000,0000,000.0}",
value);
Console.WriteLine(result);
// The example displays the following output:
// 00016342 00016342.000 0,000,016,342.0
Module Example
Public Sub Main()
Dim value As Integer = 16342
Dim result As String = String.Format("{0,18:00000000} {0,18:00000000.000} {0,18:000,0000,000.0}",
value)
Console.WriteLine(result)
End Sub
End Module
' The example displays the following output:
' 00016342 00016342.000 0,000,016,342.0
Kolik položek lze zahrnout do seznamu formátů?How many items can I include in the format list?
Neexistují žádné praktické omezení.There is no practical limit. Druhý parametr Format(IFormatProvider, String, Object[]) metody je označen ParamArrayAttribute atributem, který umožňuje zahrnout buď seznam s oddělovači, nebo pole objektu jako seznam formátu.The second parameter of the Format(IFormatProvider, String, Object[]) method is tagged with the ParamArrayAttribute attribute, which allows you to include either a delimited list or an object array as your format list.
Do výsledného řetězce Návody zahrnout literální závorky ("{" a "}")?How do I include literal braces ("{" and "}") in the result string?
Například, jak zabráníte následujícímu volání metody v vyvolání FormatException výjimky?For example, how do you prevent the following method call from throwing a FormatException exception?
result = String.Format("The text has {0} '{' characters and {1} '}' characters.",
nOpen, nClose);
result = String.Format("The text has {0} '{' characters and {1} '}' characters.",
nOpen, nClose)
Jednoduchá levá nebo pravá složená závorka je vždy interpretována jako začátek nebo konec položky formátu.A single opening or closing brace is always interpreted as the beginning or end of a format item. Aby bylo možné je interpretovat doslova, musí být uvozena řídicím znakem.To be interpreted literally, it must be escaped. Zařídíte složenou závorku přidáním další složené závorky ("{{" a "}}" místo "{" a "}"), jako v následujícím volání metody:You escape a brace by adding another brace ("{{" and "}}" instead of "{" and "}"), as in the following method call:
string result;
int nOpen = 1;
int nClose = 2;
result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.",
nOpen, nClose);
Console.WriteLine(result);
result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.",
nOpen, nClose)
Dokonce i řídící závorky jsou však snadno špatně interpretovány.However, even escaped braces are easily misinterpreted. Doporučujeme zahrnout složené závorky do seznamu formátů a použít položky formátu k jejich vložení do výsledného řetězce, jak ukazuje následující příklad.We recommend that you include braces in the format list and use format items to insert them in the result string, as the following example shows.
string result;
int nOpen = 1;
int nClose = 2;
result = String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.",
nOpen, "{", nClose, "}");
Console.WriteLine(result);
result = String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.",
nOpen, "{", nClose, "}")
Proč moje volání metody String. Format vyvolávají výjimku FormatException?Why does my call to the String.Format method throw a FormatException?
Nejběžnější příčinou výjimky je, že index položky formátu neodpovídá objektu v seznamu formát.The most common cause of the exception is that the index of a format item doesn't correspond to an object in the format list. To obvykle znamená, že jste načetli příliš mnoho indexů formátovacích položek nebo jste zapomněli zahrnout objekt do seznamu formát.Usually this indicates that you've misnumbered the indexes of format items or you've forgotten to include an object in the format list. Při pokusu o vložení znaku vlevo nebo pravé závorky se vyvolá také znak FormatException .Attempting to include an unescaped left or right brace character also throws a FormatException. V některých případech je výjimka výsledkem překlepu; například Typická chyba je nesprávné zadání "[" (levé hranaté závorky) namísto "{" (levé složené závorky).Occasionally, the exception is the result of a typo; for example, a typical mistake is to mistype "[" (the left bracket) instead of "{" (the left brace).
Pokud metoda Format (System. IFormatProvider, System. String, System. Object []) podporuje pole parametrů, proč můj kód vyvolá výjimku při použití pole?If the Format(System.IFormatProvider,System.String,System.Object[]) method supports parameter arrays, why does my code throw an exception when I use an array?
Například následující kód vyvolá FormatException výjimku:For example, the following code throws a FormatException exception:
Random rnd = new Random();
int[] numbers = new int[4];
int total = 0;
for (int ctr = 0; ctr <= 2; ctr++) {
int number = rnd.Next(1001);
numbers[ctr] = number;
total += number;
}
numbers[3] = total;
Console.WriteLine("{0} + {1} + {2} = {3}", numbers);
Imports System.Collections.Generic
Module Example
Public Sub Main()
Dim rnd As New Random()
Dim numbers(3) As Integer
Dim total As Integer = 0
For ctr = 0 To 2
Dim number As Integer = rnd.Next(1001)
numbers(ctr) = number
total += number
Next
numbers(3) = total
Console.WriteLine("{0} + {1} + {2} = {3}", numbers)
End Sub
End Module
Toto je problém řešení přetížení kompilátoru.This is a problem of compiler overload resolution. Vzhledem k tomu, že kompilátor nemůže převést pole celých čísel na pole objektů, zpracovává celočíselné pole jako jediný argument, takže volá Format(String, Object) metodu.Because the compiler cannot convert an array of integers to an object array, it treats the integer array as a single argument, so it calls the Format(String, Object) method. Výjimka je vyvolána, protože existují čtyři položky formátu, ale pouze jedna položka v seznamu formát.The exception is thrown because there are four format items but only a single item in the format list.
Vzhledem k tomu, že Visual Basic ani C# mohou převést celočíselné pole na pole objektu, je nutné provést převod sami před voláním Format(String, Object[]) metody.Because neither Visual Basic nor C# can convert an integer array to an object array, you have to perform the conversion yourself before calling the Format(String, Object[]) method. Následující příklad poskytuje jednu implementaci.The following example provides one implementation.
Random rnd = new Random();
int[] numbers = new int[4];
int total = 0;
for (int ctr = 0; ctr <= 2; ctr++) {
int number = rnd.Next(1001);
numbers[ctr] = number;
total += number;
}
numbers[3] = total;
object[] values = new object[numbers.Length];
numbers.CopyTo(values, 0);
Console.WriteLine("{0} + {1} + {2} = {3}", values);
Imports System.Collections.Generic
Module Example
Public Sub Main()
Dim rnd As New Random()
Dim numbers(3) As Integer
Dim total As Integer = 0
For ctr = 0 To 2
Dim number As Integer = rnd.Next(1001)
numbers(ctr) = number
total += number
Next
numbers(3) = total
Dim values(numbers.Length - 1) As Object
numbers.CopyTo(values, 0)
Console.WriteLine("{0} + {1} + {2} = {3}", values)
End Sub
End Module
Format(String, Object)
Nahradí jednu nebo více položek formátu v řetězci řetězcovou reprezentací zadaného objektu.Replaces one or more format items in a string with the string representation of a specified object.
public:
static System::String ^ Format(System::String ^ format, System::Object ^ arg0);
public static string Format (string format, object arg0);
public static string Format (string format, object? arg0);
static member Format : string * obj -> string
Public Shared Function Format (format As String, arg0 As Object) As String
Parametry
- arg0
- Object
Objekt, který má být zformátován.The object to format.
Návraty
Kopie, format ve které jsou formátovací položky nahrazeny řetězcovou reprezentací arg0 .A copy of format in which any format items are replaced by the string representation of arg0.
Výjimky
format je null.format is null.
Položka formátu v format je neplatná.The format item in format is invalid.
-nebo--or-
Index položky formátu není nula.The index of a format item is not zero.
Poznámky
Důležité
Namísto volání metody String. Format nebo použití složených formátovacích řetězcůmůžete použít interpolované řetězce , pokud je váš jazyk podporuje.Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. Interpolovaná řetězcová událost je řetězec, který obsahuje interpolované výrazy.An interpolated string is a string that contains interpolated expressions. Každý interpolující výraz je vyřešen s hodnotou výrazu a je zahrnut ve výsledném řetězci při přiřazení řetězce.Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. Další informace naleznete v tématu interpolace řetězce (Referenční dokumentace jazyka C#) a interpolované řetězce (Visual Basic odkaz).For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).
Tato metoda používá funkci složeného formátování k převodu hodnoty výrazu na jeho řetězcovou reprezentaci a vložení této reprezentace do řetězce.This method uses the composite formatting feature to convert the value of an expression to its string representation and to embed that representation in a string.
Nicméně při volání metody String. Format není nutné se zaměřit na konkrétní přetížení, které chcete volat.However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. Místo toho můžete zavolat metodu se složeným řetězcem formátu , který obsahuje jednu nebo více položek formátu.Instead, you can call the method with a composite format string that includes one or more format items. Každé položce formátu přiřadíte číselný index; první index začíná na 0.You assign each format item a numeric index; the first index starts at 0. Kromě počátečního řetězce by volání metody mělo mít tolik dalších argumentů, protože mají hodnoty indexu.In addition to the initial string, your method call should have as many additional arguments as it has index values. Například řetězec, jehož položky formátu mají index 0 a 1, by měl mít 2 argumenty; jeden s indexy 0 až 5 by měl mít 6 argumentů.For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. Kompilátor jazyka potom vyřeší volání metody do konkrétního přetížení metody String. Format .Your language compiler will then resolve your method call to a particular overload of the String.Format method.
Podrobnější dokumentaci k použití metody String. Format naleznete v tématu Začínáme s metodou String. Format a kterou metodou volám?.For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.
Příklad: formátování jednoho argumentuExample: Formatting a single argument
Následující příklad používá Format(String, Object) metodu pro vložení stáří jednotlivce do středu řetězce.The following example uses the Format(String, Object) method to embed an individual's age in the middle of a string.
using namespace System;
void main()
{
DateTime birthdate = DateTime(1993, 7, 28);
array<DateTime>^ dates = gcnew array<DateTime> { DateTime(1993, 8, 16),
DateTime(1994, 7, 28),
DateTime(2000, 10, 16),
DateTime(2003, 7, 27),
DateTime(2007, 5, 27) };
for each (DateTime dateValue in dates)
{
TimeSpan interval = dateValue - birthdate;
// Get the approximate number of years, without accounting for leap years.
int years = ((int)interval.TotalDays) / 365;
// See if adding the number of years exceeds dateValue.
String^ output;
if (birthdate.AddYears(years) <= dateValue) {
output = String::Format("You are now {0} years old.", years);
Console::WriteLine(output);
}
else {
output = String::Format("You are now {0} years old.", years - 1);
Console::WriteLine(output);
}
}
}
// The example displays the following output:
// You are now 0 years old.
// You are now 1 years old.
// You are now 7 years old.
// You are now 9 years old.
// You are now 13 years old.
DateTime birthdate = new DateTime(1993, 7, 28);
DateTime[] dates = { new DateTime(1993, 8, 16),
new DateTime(1994, 7, 28),
new DateTime(2000, 10, 16),
new DateTime(2003, 7, 27),
new DateTime(2007, 5, 27) };
foreach (DateTime dateValue in dates)
{
TimeSpan interval = dateValue - birthdate;
// Get the approximate number of years, without accounting for leap years.
int years = ((int) interval.TotalDays) / 365;
// See if adding the number of years exceeds dateValue.
string output;
if (birthdate.AddYears(years) <= dateValue) {
output = String.Format("You are now {0} years old.", years);
Console.WriteLine(output);
}
else {
output = String.Format("You are now {0} years old.", years - 1);
Console.WriteLine(output);
}
}
// The example displays the following output:
// You are now 0 years old.
// You are now 1 years old.
// You are now 7 years old.
// You are now 9 years old.
// You are now 13 years old.
Module Example
Public Sub Main()
Dim birthdate As Date = #7/28/1993#
Dim dates() As Date = { #9/16/1993#, #7/28/1994#, #10/16/2000#, _
#7/27/2003#, #5/27/2007# }
For Each dateValue As Date In dates
Dim interval As TimeSpan = dateValue - birthdate
' Get the approximate number of years, without accounting for leap years.
Dim years As Integer = CInt(interval.TotalDays) \ 365
' See if adding the number of years exceeds dateValue.
Dim output As String
If birthdate.AddYears(years) <= dateValue Then
output = String.Format("You are now {0} years old.", years)
Console.WriteLine(output)
Else
output = String.Format("You are now {0} years old.", years - 1)
Console.WriteLine(output)
End If
Next
End Sub
End Module
' The example displays the following output:
' You are now 0 years old.
' You are now 1 years old.
' You are now 7 years old.
' You are now 9 years old.
' You are now 13 years old.
Platí pro
Format(String, Object[])
Nahradí položku formátu v zadaném řetězci řetězcovou reprezentací odpovídajícího objektu v zadaném poli.Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.
public:
static System::String ^ Format(System::String ^ format, ... cli::array <System::Object ^> ^ args);
public static string Format (string format, params object[] args);
public static string Format (string format, params object?[] args);
static member Format : string * obj[] -> string
Public Shared Function Format (format As String, ParamArray args As Object()) As String
Parametry
- args
- Object[]
Pole objektu, které obsahuje objekty k formátování. Pole nemusí obsahovat žádný objekt.An object array that contains zero or more objects to format.
Návraty
Kopie, format ve které byly položky formátu nahrazeny řetězcovou reprezentací odpovídajících objektů v args .A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.
Výjimky
format nebo args je null .format or args is null.
Formát format je neplatný.format is invalid.
-nebo--or-
Index položky formátu je menší než nula nebo větší nebo roven délce args pole.The index of a format item is less than zero, or greater than or equal to the length of the args array.
Poznámky
Důležité
Namísto volání metody String. Format nebo použití složených formátovacích řetězcůmůžete použít interpolované řetězce , pokud je váš jazyk podporuje.Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. Interpolovaná řetězcová událost je řetězec, který obsahuje interpolované výrazy.An interpolated string is a string that contains interpolated expressions. Každý interpolující výraz je vyřešen s hodnotou výrazu a je zahrnut ve výsledném řetězci při přiřazení řetězce.Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. Další informace naleznete v tématu interpolace řetězce (Referenční dokumentace jazyka C#) a interpolované řetězce (Visual Basic odkaz).For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).
Tato metoda používá funkci složeného formátování k převodu hodnoty čtyř nebo více výrazů na jejich reprezentace řetězců a vložení těchto reprezentace do řetězce.This method uses the composite formatting feature to convert the value of four or more expressions to their string representations and to embed those representations in a string. Vzhledem k tomu args , že parametr je označen System.ParamArrayAttribute atributem, lze předat objekty metodě jako jednotlivé argumenty nebo jako Object pole.Since the args parameter is marked with the System.ParamArrayAttribute attribute, you can pass the objects to the method as individual arguments or as an Object array.
Nicméně při volání metody String. Format není nutné se zaměřit na konkrétní přetížení, které chcete volat.However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. Místo toho můžete zavolat metodu se složeným řetězcem formátu , který obsahuje jednu nebo více položek formátu.Instead, you can call the method with a composite format string that includes one or more format items. Každé položce formátu přiřadíte číselný index; první index začíná na 0.You assign each format item a numeric index; the first index starts at 0. Kromě počátečního řetězce by volání metody mělo mít tolik dalších argumentů, protože mají hodnoty indexu.In addition to the initial string, your method call should have as many additional arguments as it has index values. Například řetězec, jehož položky formátu mají index 0 a 1, by měl mít 2 argumenty; jeden s indexy 0 až 5 by měl mít 6 argumentů.For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. Kompilátor jazyka potom vyřeší volání metody do konkrétního přetížení metody String. Format .Your language compiler will then resolve your method call to a particular overload of the String.Format method.
Podrobnější dokumentaci k použití metody String. Format naleznete v tématu Začínáme s metodou String. Format a kterou metodou volám?.For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.
Příklad: formátování více než tří argumentůExample: Format more than three arguments
Tento příklad vytvoří řetězec, který obsahuje data o vysoké a nízké teplotě určitého data.This example creates a string that contains data on the high and low temperature on a particular date. Složený formátovací řetězec má pět položek formátu v příkladu C# a šest v příkladu Visual Basic.The composite format string has five format items in the C# example and six in the Visual Basic example. Dvě položky formátu definují šířku řetězcové reprezentace příslušné hodnoty a první položka formátu obsahuje také standardní formátovací řetězec data a času.Two of the format items define the width of their corresponding value's string representation, and the first format item also includes a standard date and time format string.
using namespace System;
void main()
{
DateTime date1 = DateTime(2009, 7, 1);
TimeSpan hiTime = TimeSpan(14, 17, 32);
Decimal hiTemp = (Decimal) 62.1;
TimeSpan loTime = TimeSpan(3, 16, 10);
Decimal loTemp = (Decimal)54.8;
String^ result1 = String::Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)",
date1, hiTime, hiTemp, loTime, loTemp);
Console::WriteLine(result1);
Console::WriteLine();
String^ result2 = String::Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)",
gcnew array<Object^> { date1, hiTime, hiTemp, loTime, loTemp });
Console::WriteLine(result2);
}
// The example displays the following output:
// Temperature on 7/1/2009:
// 14:17:32: 62.1 degrees (hi)
// 03:16:10: 54.8 degrees (lo)
// Temperature on 7/1/2009:
// 14:17:32: 62.1 degrees (hi)
// 03:16:10: 54.8 degrees (lo)
DateTime date1 = new DateTime(2009, 7, 1);
TimeSpan hiTime = new TimeSpan(14, 17, 32);
decimal hiTemp = 62.1m;
TimeSpan loTime = new TimeSpan(3, 16, 10);
decimal loTemp = 54.8m;
string result1 = String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)",
date1, hiTime, hiTemp, loTime, loTemp);
Console.WriteLine(result1);
Console.WriteLine();
string result2 = String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)",
new object[] { date1, hiTime, hiTemp, loTime, loTemp });
Console.WriteLine(result2);
// The example displays output like the following:
// Temperature on 7/1/2009:
// 14:17:32: 62.1 degrees (hi)
// 03:16:10: 54.8 degrees (lo)
// Temperature on 7/1/2009:
// 14:17:32: 62.1 degrees (hi)
// 03:16:10: 54.8 degrees (lo)
Module Example
Public Sub Main()
Dim date1 As Date = #7/1/2009#
Dim hiTime As New TimeSpan(14, 17, 32)
Dim hiTemp As Decimal = 62.1d
Dim loTime As New TimeSpan(3, 16, 10)
Dim loTemp As Decimal = 54.8d
Dim result1 As String = String.Format("Temperature on {0:d}:{5}{1,11}: {2} degrees (hi){5}{3,11}: {4} degrees (lo)", _
date1, hiTime, hiTemp, loTime, loTemp, vbCrLf)
Console.WriteLine(result1)
Console.WriteLine()
Dim result2 As String = String.Format("Temperature on {0:d}:{5}{1,11}: {2} degrees (hi){5}{3,11}: {4} degrees (lo)", _
New Object() { date1, hiTime, hiTemp, loTime, loTemp, vbCrLf })
Console.WriteLine(result2)
End Sub
End Module
' The example displays the following output:
' Temperature on 7/1/2009:
' 14:17:32: 62.1 degrees (hi)
' 03:16:10: 54.8 degrees (lo)
'
' Temperature on 7/1/2009:
' 14:17:32: 62.1 degrees (hi)
' 03:16:10: 54.8 degrees (lo)
Můžete také předat objekty, které mají být formátovány jako pole, nikoli jako seznam argumentů.You can also pass the objects to be formatted as an array rather than as an argument list.
using namespace System;
ref class CityInfo
{
public:
CityInfo(String^ name, int population, Decimal area, int year)
{
this->Name = name;
this->Population = population;
this->Area = area;
this->Year = year;
}
String^ Name;
int Population;
Decimal Area;
int Year;
};
ref class Example
{
public:
static void ShowPopulationData(CityInfo^ city)
{
array<Object^>^ args = gcnew array<Object^> { city->Name, city->Year, city->Population, city->Area };
String^ result = String::Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet",
args);
Console::WriteLine(result);
}
};
void main()
{
CityInfo^ nyc2010 = gcnew CityInfo("New York", 8175133, (Decimal) 302.64, 2010);
Example::ShowPopulationData(nyc2010);
CityInfo^ sea2010 = gcnew CityInfo("Seattle", 608660, (Decimal) 83.94, 2010);
Example::ShowPopulationData(sea2010);
}
// The example displays the following output:
// New York in 2010: Population 8,175,133, Area 302.6 sq. feet
// Seattle in 2010: Population 608,660, Area 83.9 sq. feet
using System;
public class CityInfo
{
public CityInfo(String name, int population, Decimal area, int year)
{
this.Name = name;
this.Population = population;
this.Area = area;
this.Year = year;
}
public readonly String Name;
public readonly int Population;
public readonly Decimal Area;
public readonly int Year;
}
public class Example
{
public static void Main()
{
CityInfo nyc2010 = new CityInfo("New York", 8175133, 302.64m, 2010);
ShowPopulationData(nyc2010);
CityInfo sea2010 = new CityInfo("Seattle", 608660, 83.94m, 2010);
ShowPopulationData(sea2010);
}
private static void ShowPopulationData(CityInfo city)
{
object[] args = { city.Name, city.Year, city.Population, city.Area };
String result = String.Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet",
args);
Console.WriteLine(result);
}
}
// The example displays the following output:
// New York in 2010: Population 8,175,133, Area 302.6 sq. feet
// Seattle in 2010: Population 608,660, Area 83.9 sq. feet
Public Class CityInfo
Public Sub New(name As String, population As Integer, area As Decimal, year As Integer)
Me.Name = name
Me.Population = population
Me.Area = area
Me.Year = year
End Sub
Public ReadOnly Name As String
Public ReadOnly Population As Integer
Public ReadOnly Area As Decimal
Public ReadOnly Year As Integer
End Class
Module Example
Public Sub Main()
Dim nyc2010 As New CityInfo("New York", 8175133, 302.64d, 2010)
ShowPopulationData(nyc2010)
Dim sea2010 As New CityInfo("Seattle", 608660, 83.94d, 2010)
ShowPopulationData(sea2010)
End Sub
Private Sub ShowPopulationData(city As CityInfo)
Dim args() As Object = { city.Name, city.Year, city.Population, city.Area }
Dim result = String.Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet", args)
Console.WriteLine(result)
End Sub
End Module
' The example displays the following output:
' New York in 2010: Population 8,175,133, Area 302.6 sq. feet
' Seattle in 2010: Population 608,660, Area 83.9 sq. feet
Platí pro
Format(IFormatProvider, String, Object)
Nahradí položku formátu nebo položky v zadaném řetězci řetězcovou reprezentací odpovídajícího objektu.Replaces the format item or items in a specified string with the string representation of the corresponding object. Parametr poskytuje informace o formátování specifické pro jazykovou verzi.A parameter supplies culture-specific formatting information.
public:
static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0);
public static string Format (IFormatProvider provider, string format, object arg0);
public static string Format (IFormatProvider? provider, string format, object? arg0);
static member Format : IFormatProvider * string * obj -> string
Public Shared Function Format (provider As IFormatProvider, format As String, arg0 As Object) As String
Parametry
- provider
- IFormatProvider
Objekt, který poskytuje informace o formátování specifické pro jazykovou verzi.An object that supplies culture-specific formatting information.
- arg0
- Object
Objekt, který má být zformátován.The object to format.
Návraty
Kopie, format ve které byla položka formátu nebo položky nahrazena řetězcovou reprezentací arg0 .A copy of format in which the format item or items have been replaced by the string representation of arg0.
Výjimky
format je null.format is null.
Formát format je neplatný.format is invalid.
-nebo--or-
Index položky formátu není nula.The index of a format item is not zero.
Poznámky
Důležité
Namísto volání metody String. Format nebo použití složených formátovacích řetězcůmůžete použít interpolované řetězce , pokud je váš jazyk podporuje.Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. Interpolovaná řetězcová událost je řetězec, který obsahuje interpolované výrazy.An interpolated string is a string that contains interpolated expressions. Každý interpolující výraz je vyřešen s hodnotou výrazu a je zahrnut ve výsledném řetězci při přiřazení řetězce.Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. Další informace naleznete v tématu interpolace řetězce (Referenční dokumentace jazyka C#) a interpolované řetězce (Visual Basic odkaz).For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).
Tato metoda používá funkci složeného formátování k převodu hodnoty výrazu na jeho řetězcovou reprezentaci a vložení této reprezentace do řetězce.This method uses the composite formatting feature to convert the value of an expression to its string representation and to embed that representation in a string. Při provádění převodu používá metoda formátování zohledňující jazykovou verzi nebo vlastní formátovací modul.In performing the conversion, the method uses culture-sensitive formatting or a custom formatter. Metoda se převede arg0 na své řetězcové vyjádření voláním metody ToString (IFormatProvider) nebo, pokud odpovídající položka formátu objektu obsahuje řetězec formátu, voláním metody ToString (String, IFormatProvider) .The method converts arg0 to its string representation by calling its ToString(IFormatProvider) method or, if the object's corresponding format item includes a format string, by calling its ToString(String,IFormatProvider) method. Pokud tyto metody neexistují, volá metodu ToString bez parametrů objektu.If these methods don't exist, it calls the object's parameterless ToString method.
Nicméně při volání metody String. Format není nutné se zaměřit na konkrétní přetížení, které chcete volat.However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. Místo toho můžete zavolat metodu s objektem, který poskytuje jazykově závislé nebo vlastní formátování a složený řetězec formátu , který obsahuje jednu nebo více položek formátu.Instead, you can call the method with an object that provides culture-sensitive or custom formatting and a composite format string that includes one or more format items. Každé položce formátu přiřadíte číselný index; první index začíná na 0.You assign each format item a numeric index; the first index starts at 0. Kromě počátečního řetězce by volání metody mělo mít tolik dalších argumentů, protože mají hodnoty indexu.In addition to the initial string, your method call should have as many additional arguments as it has index values. Například řetězec, jehož položky formátu mají index 0 a 1, by měl mít 2 argumenty; jeden s indexy 0 až 5 by měl mít 6 argumentů.For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. Kompilátor jazyka potom vyřeší volání metody do konkrétního přetížení metody String. Format .Your language compiler will then resolve your method call to a particular overload of the String.Format method.
Podrobnější dokumentaci k použití metody String. Format naleznete v tématu Začínáme s metodou String. Format a kterou metodou volám?.For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.
Platí pro
Format(IFormatProvider, String, Object[])
Nahradí položky formátu v řetězci řetězcovými reprezentacemi odpovídajících objektů v zadaném poli.Replaces the format items in a string with the string representations of corresponding objects in a specified array. Parametr poskytuje informace o formátování specifické pro jazykovou verzi.A parameter supplies culture-specific formatting information.
public:
static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, ... cli::array <System::Object ^> ^ args);
public static string Format (IFormatProvider provider, string format, params object[] args);
public static string Format (IFormatProvider? provider, string format, params object?[] args);
static member Format : IFormatProvider * string * obj[] -> string
Public Shared Function Format (provider As IFormatProvider, format As String, ParamArray args As Object()) As String
Parametry
- provider
- IFormatProvider
Objekt, který poskytuje informace o formátování specifické pro jazykovou verzi.An object that supplies culture-specific formatting information.
- args
- Object[]
Pole objektu, které obsahuje objekty k formátování. Pole nemusí obsahovat žádný objekt.An object array that contains zero or more objects to format.
Návraty
Kopie, format ve které byly položky formátu nahrazeny řetězcovou reprezentací odpovídajících objektů v args .A copy of format in which the format items have been replaced by the string representation of the corresponding objects in args.
Výjimky
format nebo args je null .format or args is null.
Formát format je neplatný.format is invalid.
-nebo--or-
Index položky formátu je menší než nula nebo větší nebo roven délce args pole.The index of a format item is less than zero, or greater than or equal to the length of the args array.
Poznámky
Důležité
Namísto volání metody String. Format nebo použití složených formátovacích řetězcůmůžete použít interpolované řetězce , pokud je váš jazyk podporuje.Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. Interpolovaná řetězcová událost je řetězec, který obsahuje interpolované výrazy.An interpolated string is a string that contains interpolated expressions. Každý interpolující výraz je vyřešen s hodnotou výrazu a je zahrnut ve výsledném řetězci při přiřazení řetězce.Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. Další informace naleznete v tématu interpolace řetězce (Referenční dokumentace jazyka C#) a interpolované řetězce (Visual Basic odkaz).For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).
Tato metoda používá funkci složeného formátování k převodu čtyř nebo více výrazů na jejich reprezentace řetězců a vložení těchto reprezentace do řetězce.This method uses the composite formatting feature to convert four or more expressions to their string representations and to embed those representations in a string. Při provádění převodu používá metoda formátování zohledňující jazykovou verzi nebo vlastní formátovací modul.In performing the conversion, the method uses culture-sensitive formatting or a custom formatter. Metoda převede každý Object argument na jeho řetězcovou reprezentaci voláním metody ToString (IFormatProvider) nebo, pokud odpovídající položka formátu objektu obsahuje řetězec formátu, voláním metody ToString (String, IFormatProvider) .The method converts each Object argument to its string representation by calling its ToString(IFormatProvider) method or, if the object's corresponding format item includes a format string, by calling its ToString(String,IFormatProvider) method. Pokud tyto metody neexistují, volá metodu ToString bez parametrů objektu.If these methods don't exist, it calls the object's parameterless ToString method.
Nicméně při volání metody String. Format není nutné se zaměřit na konkrétní přetížení, které chcete volat.However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. Místo toho můžete zavolat metodu s objektem, který poskytuje jazykově závislé nebo vlastní formátování a složený řetězec formátu , který obsahuje jednu nebo více položek formátu.Instead, you can call the method with an object that provides culture-sensitive or custom formatting and a composite format string that includes one or more format items. Každé položce formátu přiřadíte číselný index; první index začíná na 0.You assign each format item a numeric index; the first index starts at 0. Kromě počátečního řetězce by volání metody mělo mít tolik dalších argumentů, protože mají hodnoty indexu.In addition to the initial string, your method call should have as many additional arguments as it has index values. Například řetězec, jehož položky formátu mají index 0 a 1, by měl mít 2 argumenty; jeden s indexy 0 až 5 by měl mít 6 argumentů.For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. Kompilátor jazyka potom vyřeší volání metody do konkrétního přetížení metody String. Format .Your language compiler will then resolve your method call to a particular overload of the String.Format method.
Podrobnější dokumentaci k použití metody String. Format naleznete v tématu Začínáme s metodou String. Format a kterou metodou volám?.For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.
Příklad: formátování zohledňující jazykovou verziExample: Culture-sensitive formatting
Tento příklad používá Format(IFormatProvider, String, Object[]) metodu k zobrazení řetězcové reprezentace některých hodnot data a času a číselných hodnot pomocí několika různých kultur.This example uses the Format(IFormatProvider, String, Object[]) method to display the string representation of some date and time values and numeric values by using several different cultures.
string[] cultureNames = { "en-US", "fr-FR", "de-DE", "es-ES" };
DateTime dateToDisplay = new DateTime(2009, 9, 1, 18, 32, 0);
double value = 9164.32;
Console.WriteLine("Culture Date Value\n");
foreach (string cultureName in cultureNames)
{
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(cultureName);
string output = String.Format(culture, "{0,-11} {1,-35:D} {2:N}",
culture.Name, dateToDisplay, value);
Console.WriteLine(output);
}
// The example displays the following output:
// Culture Date Value
//
// en-US Tuesday, September 01, 2009 9,164.32
// fr-FR mardi 1 septembre 2009 9 164,32
// de-DE Dienstag, 1. September 2009 9.164,32
// es-ES martes, 01 de septiembre de 2009 9.164,32
Imports System.Globalization
Module Example
Public Sub Main()
Dim cultureNames() As String = { "en-US", "fr-FR", "de-DE", "es-ES" }
Dim dateToDisplay As Date = #9/1/2009 6:32PM#
Dim value As Double = 9164.32
Console.WriteLine("Culture Date Value")
Console.WriteLine()
For Each cultureName As String In cultureNames
Dim culture As New CultureInfo(cultureName)
Dim output As String = String.Format(culture, "{0,-11} {1,-35:D} {2:N}", _
culture.Name, dateToDisplay, value)
Console.WriteLine(output)
Next
End Sub
End Module
' The example displays the following output:
' Culture Date Value
'
' en-US Tuesday, September 01, 2009 9,164.32
' fr-FR mardi 1 septembre 2009 9 164,32
' de-DE Dienstag, 1. September 2009 9.164,32
' es-ES martes, 01 de septiembre de 2009 9.164,32
Viz také
- DateTimeFormatInfo
- ICustomFormatter
- IFormatProvider
- NumberFormatInfo
- Formátování typů v .NETFormatting Types in .NET
- Složené formátováníComposite Formatting
- Standardní řetězce formátu data a časuStandard Date and Time Format Strings
- Vlastní řetězce formátu data a časuCustom Date and Time Format Strings
- Standardní řetězce formátu číslaStandard Numeric Format Strings
- Vlastní řetězce číselného formátuCustom Numeric Format Strings
- Standardní řetězce formátu TimeSpanStandard TimeSpan Format Strings
- Vlastní řetězce formátu TimeSpanCustom TimeSpan Format Strings
- Vytvoření výčtu řetězců formátuEnumeration Format Strings
Platí pro
Format(String, Object, Object)
Nahradí položky formátu v řetězci řetězcovou reprezentací dvou zadaných objektů.Replaces the format items in a string with the string representation of two specified objects.
public:
static System::String ^ Format(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1);
public static string Format (string format, object arg0, object arg1);
public static string Format (string format, object? arg0, object? arg1);
static member Format : string * obj * obj -> string
Public Shared Function Format (format As String, arg0 As Object, arg1 As Object) As String
Parametry
- arg0
- Object
První objekt pro formátování.The first object to format.
- arg1
- Object
Druhý objekt pro formátování.The second object to format.
Návraty
Kopie, format ve které jsou formátovací položky nahrazeny řetězcovými reprezentacemi arg0 a arg1 .A copy of format in which format items are replaced by the string representations of arg0 and arg1.
Výjimky
format je null.format is null.
Formát format je neplatný.format is invalid.
-nebo--or-
Index položky formátu není nula nebo jedna.The index of a format item is not zero or one.
Poznámky
Důležité
Namísto volání metody String. Format nebo použití složených formátovacích řetězcůmůžete použít interpolované řetězce , pokud je váš jazyk podporuje.Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. Interpolovaná řetězcová událost je řetězec, který obsahuje interpolované výrazy.An interpolated string is a string that contains interpolated expressions. Každý interpolující výraz je vyřešen s hodnotou výrazu a je zahrnut ve výsledném řetězci při přiřazení řetězce.Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. Další informace naleznete v tématu interpolace řetězce (Referenční dokumentace jazyka C#) a interpolované řetězce (Visual Basic odkaz).For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).
Tato metoda používá funkci složeného formátování k převodu hodnoty dvou výrazů na jejich reprezentace řetězců a vložení těchto reprezentace do řetězce.This method uses the composite formatting feature to convert the value of two expressions to their string representations and to embed those representations in a string.
Nicméně při volání metody String. Format není nutné se zaměřit na konkrétní přetížení, které chcete volat.However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. Místo toho můžete zavolat metodu se složeným řetězcem formátu , který obsahuje jednu nebo více položek formátu.Instead, you can call the method with a composite format string that includes one or more format items. Každé položce formátu přiřadíte číselný index; první index začíná na 0.You assign each format item a numeric index; the first index starts at 0. Kromě počátečního řetězce by volání metody mělo mít tolik dalších argumentů, protože mají hodnoty indexu.In addition to the initial string, your method call should have as many additional arguments as it has index values. Například řetězec, jehož položky formátu mají index 0 a 1, by měl mít 2 argumenty; jeden s indexy 0 až 5 by měl mít 6 argumentů.For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. Kompilátor jazyka potom vyřeší volání metody do konkrétního přetížení metody String. Format .Your language compiler will then resolve your method call to a particular overload of the String.Format method.
Podrobnější dokumentaci k použití metody String. Format naleznete v tématu Začínáme s metodou String. Format a kterou metodou volám?.For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.
Příklad: formátování dvou argumentůExample: Format two arguments
Tento příklad používá Format(String, Object, Object) metodu k zobrazení času a dat teploty uložených v obecném Dictionary<TKey,TValue> objektu.This example uses the Format(String, Object, Object) method to display time and temperature data stored in a generic Dictionary<TKey,TValue> object. Všimněte si, že formátovací řetězec má tři položky formátu, i když existují pouze dva objekty k formátování.Note that the format string has three format items, although there are only two objects to format. Důvodem je, že první objekt v seznamu (hodnota datum a čas) je použit dvěma položkami formátu: první položka formátu zobrazuje čas a druhá zobrazí datum.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 namespace System;
using namespace System::Collections::Generic;
void main()
{
Dictionary<DateTime, Double>^ temperatureInfo = gcnew Dictionary<DateTime, Double>();
temperatureInfo->Add(DateTime(2010, 6, 1, 14, 0, 0), 87.46);
temperatureInfo->Add(DateTime(2010, 12, 1, 10, 0, 0), 36.81);
Console::WriteLine("Temperature Information:\n");
String^ output;
for each (KeyValuePair<DateTime, Double>^ item in temperatureInfo)
{
output = String::Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}�F",
item->Key, item->Value);
Console::WriteLine(output);
}
}
// 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
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);
Console.WriteLine("Temperature Information:\n");
string output;
foreach (var item in temperatureInfo)
{
output = String.Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F",
item.Key, item.Value);
Console.WriteLine(output);
}
// The example displays output like the following:
// 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
Module Example
Public Sub Main()
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)
Console.WriteLine("Temperature Information:")
Console.WriteLine()
Dim output As String
For Each item In temperatureInfo
output = String.Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F", _
item.Key, item.Value)
Console.WriteLine(output)
Next
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
Platí pro
Format(IFormatProvider, String, Object, Object)
Nahradí položky formátu v řetězci řetězcovou reprezentací dvou zadaných objektů.Replaces the format items in a string with the string representation of two specified objects. Parametr poskytuje informace o formátování specifické pro jazykovou verzi.A parameter supplies culture-specific formatting information.
public:
static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0, System::Object ^ arg1);
public static string Format (IFormatProvider provider, string format, object arg0, object arg1);
public static string Format (IFormatProvider? provider, string format, object? arg0, object? arg1);
static member Format : IFormatProvider * string * obj * obj -> string
Public Shared Function Format (provider As IFormatProvider, format As String, arg0 As Object, arg1 As Object) As String
Parametry
- provider
- IFormatProvider
Objekt, který poskytuje informace o formátování specifické pro jazykovou verzi.An object that supplies culture-specific formatting information.
- arg0
- Object
První objekt pro formátování.The first object to format.
- arg1
- Object
Druhý objekt pro formátování.The second object to format.
Návraty
Kopie, format ve které jsou formátovací položky nahrazeny řetězcovými reprezentacemi arg0 a arg1 .A copy of format in which format items are replaced by the string representations of arg0 and arg1.
Výjimky
format je null.format is null.
Formát format je neplatný.format is invalid.
-nebo--or-
Index položky formátu není nula nebo jedna.The index of a format item is not zero or one.
Poznámky
Důležité
Namísto volání metody String. Format nebo použití složených formátovacích řetězcůmůžete použít interpolované řetězce , pokud je váš jazyk podporuje.Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. Interpolovaná řetězcová událost je řetězec, který obsahuje interpolované výrazy.An interpolated string is a string that contains interpolated expressions. Každý interpolující výraz je vyřešen s hodnotou výrazu a je zahrnut ve výsledném řetězci při přiřazení řetězce.Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. Další informace naleznete v tématu interpolace řetězce (Referenční dokumentace jazyka C#) a interpolované řetězce (Visual Basic odkaz).For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).
Tato metoda používá funkci složeného formátování k převodu dvou výrazů na reprezentace řetězců a vložení těchto reprezentace do řetězce.This method uses the composite formatting feature to convert two expressions to their string representations and to embed those representations in a string. Při provádění převodu používá metoda formátování zohledňující jazykovou verzi nebo vlastní formátovací modul.In performing the conversion, the method uses culture-sensitive formatting or a custom formatter. Metoda převede každý Object argument na jeho řetězcovou reprezentaci voláním metody ToString (IFormatProvider) nebo, pokud odpovídající položka formátu objektu obsahuje řetězec formátu, voláním metody ToString (String, IFormatProvider) .The method converts each Object argument to its string representation by calling its ToString(IFormatProvider) method or, if the object's corresponding format item includes a format string, by calling its ToString(String,IFormatProvider) method. Pokud tyto metody neexistují, volá metodu ToString bez parametrů objektu.If these methods don't exist, it calls the object's parameterless ToString method.
Nicméně při volání metody String. Format není nutné se zaměřit na konkrétní přetížení, které chcete volat.However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. Místo toho můžete zavolat metodu s objektem, který poskytuje jazykově závislé nebo vlastní formátování a složený řetězec formátu , který obsahuje jednu nebo více položek formátu.Instead, you can call the method with an object that provides culture-sensitive or custom formatting and a composite format string that includes one or more format items. Každé položce formátu přiřadíte číselný index; první index začíná na 0.You assign each format item a numeric index; the first index starts at 0. Kromě počátečního řetězce by volání metody mělo mít tolik dalších argumentů, protože mají hodnoty indexu.In addition to the initial string, your method call should have as many additional arguments as it has index values. Například řetězec, jehož položky formátu mají index 0 a 1, by měl mít 2 argumenty; jeden s indexy 0 až 5 by měl mít 6 argumentů.For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. Kompilátor jazyka potom vyřeší volání metody do konkrétního přetížení metody String. Format .Your language compiler will then resolve your method call to a particular overload of the String.Format method.
Podrobnější dokumentaci k použití metody String. Format naleznete v tématu Začínáme s metodou String. Format a kterou metodou volám?.For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.
Platí pro
Format(String, Object, Object, Object)
Nahradí položky formátu v řetězci řetězcovou reprezentací tří zadaných objektů.Replaces the format items in a string with the string representation of three specified objects.
public:
static System::String ^ Format(System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2);
public static string Format (string format, object arg0, object arg1, object arg2);
public static string Format (string format, object? arg0, object? arg1, object? arg2);
static member Format : string * obj * obj * obj -> string
Public Shared Function Format (format As String, arg0 As Object, arg1 As Object, arg2 As Object) As String
Parametry
- arg0
- Object
První objekt pro formátování.The first object to format.
- arg1
- Object
Druhý objekt pro formátování.The second object to format.
- arg2
- Object
Třetí objekt pro formátování.The third object to format.
Návraty
Kopie format , ve které byly položky formátu nahrazeny řetězcovými reprezentacemi arg0 , arg1 a arg2 .A copy of format in which the format items have been replaced by the string representations of arg0, arg1, and arg2.
Výjimky
format je null.format is null.
Formát format je neplatný.format is invalid.
-nebo--or-
Index položky formátu je menší než nula nebo větší než dvě.The index of a format item is less than zero, or greater than two.
Poznámky
Důležité
Namísto volání metody String. Format nebo použití složených formátovacích řetězcůmůžete použít interpolované řetězce , pokud je váš jazyk podporuje.Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. Interpolovaná řetězcová událost je řetězec, který obsahuje interpolované výrazy.An interpolated string is a string that contains interpolated expressions. Každý interpolující výraz je vyřešen s hodnotou výrazu a je zahrnut ve výsledném řetězci při přiřazení řetězce.Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. Další informace naleznete v tématu interpolace řetězce (Referenční dokumentace jazyka C#) a interpolované řetězce (Visual Basic odkaz).For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).
Tato metoda používá funkci složeného formátování k převodu hodnoty tří výrazů na jejich reprezentace řetězců a vložení těchto reprezentace do řetězce.This method uses the composite formatting feature to convert the value of three expressions to their string representations and to embed those representations in a string.
Nicméně při volání metody String. Format není nutné se zaměřit na konkrétní přetížení, které chcete volat.However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. Místo toho můžete zavolat metodu se složeným řetězcem formátu , který obsahuje jednu nebo více položek formátu.Instead, you can call the method with a composite format string that includes one or more format items. Každé položce formátu přiřadíte číselný index; první index začíná na 0.You assign each format item a numeric index; the first index starts at 0. Kromě počátečního řetězce by volání metody mělo mít tolik dalších argumentů, protože mají hodnoty indexu.In addition to the initial string, your method call should have as many additional arguments as it has index values. Například řetězec, jehož položky formátu mají index 0 a 1, by měl mít 2 argumenty; jeden s indexy 0 až 5 by měl mít 6 argumentů.For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. Kompilátor jazyka potom vyřeší volání metody do konkrétního přetížení metody String. Format .Your language compiler will then resolve your method call to a particular overload of the String.Format method.
Podrobnější dokumentaci k použití metody String. Format naleznete v tématu Začínáme s metodou String. Format a kterou metodou volám?.For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.
Příklad: formátování tří argumentůExample: Format three arguments
Tento příklad používá Format(String, Object, Object, Object) metodu k vytvoření řetězce, který ilustruje výsledek logické And operace se dvěma celočíselnými hodnotami.This example uses the Format(String, Object, Object, Object) method to create a string that illustrates the result of a Boolean And operation with two integer values. Všimněte si, že formátovací řetězec obsahuje šest formátovacích položek, ale metoda má v seznamu parametrů pouze tři položky, protože každá položka je formátována dvěma různými způsoby.Note that the format string includes six format items, but the method has only three items in its parameter list, because each item is formatted in two different ways.
using namespace System;
void main()
{
String^ formatString = " {0,10} ({0,8:X8})\n" +
"And {1,10} ({1,8:X8})\n" +
" = {2,10} ({2,8:X8})";
int value1 = 16932;
int value2 = 15421;
String^ result = String::Format(formatString,
value1, value2, value1 & value2);
Console::WriteLine(result);
}
// The example displays the following output:
// 16932 (00004224)
// And 15421 (00003C3D)
// = 36 (00000024)
string formatString = " {0,10} ({0,8:X8})\n" +
"And {1,10} ({1,8:X8})\n" +
" = {2,10} ({2,8:X8})";
int value1 = 16932;
int value2 = 15421;
string result = String.Format(formatString,
value1, value2, value1 & value2);
Console.WriteLine(result);
// The example displays the following output:
// 16932 (00004224)
// And 15421 (00003C3D)
// = 36 (00000024)
Public Module Example
Public Sub Main()
Dim formatString As String = " {0,10} ({0,8:X8})" + vbCrLf + _
"And {1,10} ({1,8:X8})" + vbCrLf + _
" = {2,10} ({2,8:X8})"
Dim value1 As Integer = 16932
Dim value2 As Integer = 15421
Dim result As String = String.Format(formatString, _
value1, value2, value1 And value2)
Console.WriteLine(result)
End Sub
End Module
' The example displays the following output:
' 16932 (00004224)
' And 15421 (00003C3D)
' = 36 (00000024)
Platí pro
Format(IFormatProvider, String, Object, Object, Object)
Nahradí položky formátu v řetězci řetězcovou reprezentací tří zadaných objektů.Replaces the format items in a string with the string representation of three specified objects. Parametr poskytuje informace o formátování specifické pro jazykovou verzi.An parameter supplies culture-specific formatting information.
public:
static System::String ^ Format(IFormatProvider ^ provider, System::String ^ format, System::Object ^ arg0, System::Object ^ arg1, System::Object ^ arg2);
public static string Format (IFormatProvider provider, string format, object arg0, object arg1, object arg2);
public static string Format (IFormatProvider? provider, string format, object? arg0, object? arg1, object? arg2);
static member Format : IFormatProvider * string * obj * obj * obj -> string
Public Shared Function Format (provider As IFormatProvider, format As String, arg0 As Object, arg1 As Object, arg2 As Object) As String
Parametry
- provider
- IFormatProvider
Objekt, který poskytuje informace o formátování specifické pro jazykovou verzi.An object that supplies culture-specific formatting information.
- arg0
- Object
První objekt pro formátování.The first object to format.
- arg1
- Object
Druhý objekt pro formátování.The second object to format.
- arg2
- Object
Třetí objekt pro formátování.The third object to format.
Návraty
Kopie format , ve které byly položky formátu nahrazeny řetězcovými reprezentacemi arg0 , arg1 a arg2 .A copy of format in which the format items have been replaced by the string representations of arg0, arg1, and arg2.
Výjimky
format je null.format is null.
Formát format je neplatný.format is invalid.
-nebo--or-
Index položky formátu je menší než nula nebo větší než dvě.The index of a format item is less than zero, or greater than two.
Poznámky
Důležité
Namísto volání metody String. Format nebo použití složených formátovacích řetězcůmůžete použít interpolované řetězce , pokud je váš jazyk podporuje.Instead of calling the String.Format method or using composite format strings, you can use interpolated strings if your language supports them. Interpolovaná řetězcová událost je řetězec, který obsahuje interpolované výrazy.An interpolated string is a string that contains interpolated expressions. Každý interpolující výraz je vyřešen s hodnotou výrazu a je zahrnut ve výsledném řetězci při přiřazení řetězce.Each interpolated expression is resolved with the expression's value and included in the result string when the string is assigned. Další informace naleznete v tématu interpolace řetězce (Referenční dokumentace jazyka C#) a interpolované řetězce (Visual Basic odkaz).For more information, see String interpolation (C# Reference) and Interpolated Strings (Visual Basic Reference).
Tato metoda používá funkci složeného formátování k převodu tří výrazů na reprezentace řetězců a vložení těchto reprezentace do řetězce.This method uses the composite formatting feature to convert three expressions to their string representations and to embed those representations in a string. Při provádění převodu používá metoda formátování zohledňující jazykovou verzi nebo vlastní formátovací modul.In performing the conversion, the method uses culture-sensitive formatting or a custom formatter. Metoda převede každý Object argument na jeho řetězcovou reprezentaci voláním metody ToString (IFormatProvider) nebo, pokud odpovídající položka formátu objektu obsahuje řetězec formátu, voláním metody ToString (String, IFormatProvider) .The method converts each Object argument to its string representation by calling its ToString(IFormatProvider) method or, if the object's corresponding format item includes a format string, by calling its ToString(String,IFormatProvider) method. Pokud tyto metody neexistují, volá metodu ToString bez parametrů objektu.If these methods don't exist, it calls the object's parameterless ToString method.
Nicméně při volání metody String. Format není nutné se zaměřit na konkrétní přetížení, které chcete volat.However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. Místo toho můžete zavolat metodu s objektem, který poskytuje jazykově závislé nebo vlastní formátování a složený řetězec formátu , který obsahuje jednu nebo více položek formátu.Instead, you can call the method with an object that provides culture-sensitive or custom formatting and a composite format string that includes one or more format items. Každé položce formátu přiřadíte číselný index; první index začíná na 0.You assign each format item a numeric index; the first index starts at 0. Kromě počátečního řetězce by volání metody mělo mít tolik dalších argumentů, protože mají hodnoty indexu.In addition to the initial string, your method call should have as many additional arguments as it has index values. Například řetězec, jehož položky formátu mají index 0 a 1, by měl mít 2 argumenty; jeden s indexy 0 až 5 by měl mít 6 argumentů.For example, a string whose format items have indexes of 0 and 1 should have 2 arguments; one with indexes 0 through 5 should have 6 arguments. Kompilátor jazyka potom vyřeší volání metody do konkrétního přetížení metody String. Format .Your language compiler will then resolve your method call to a particular overload of the String.Format method.
Podrobnější dokumentaci k použití metody String. Format naleznete v tématu Začínáme s metodou String. Format a kterou metodou volám?.For more detailed documentation on using the String.Format method, see Getting started with the String.Format method and Which method do I call?.