Share via


System.String.Format yöntemi

Bu makale, bu API'nin başvuru belgelerine ek açıklamalar sağlar.

Önemli

String.Format yöntemini çağırmak veya bileşik biçim dizelerini kullanmak yerine, diliniz bunları destekliyorsa ilişkilendirilmiş dizeler kullanabilirsiniz. İlişkili dize, ilişkilendirilmiş ifadeler içeren bir dizedir. İlişkili her ifade, ifadenin değeriyle çözümlenir ve dize atandığında sonuç dizesine eklenir. Daha fazla bilgi için bkz . Dize ilişkilendirmesi (C# Başvurusu) ve İlişkili Dizeler (Visual Basic Başvurusu).

Örnekler

Yöntemini çağıran Format çok sayıda örnek, bu makale boyunca birbirine geçirilir. Ayrıca, C# için bir .NET Core projesi içeren eksiksiz bir örnek kümesini String.Format de indirebilirsiniz.

Makaledeki örneklerden bazıları şunlardır:

Biçim dizesi oluşturma

Dize ekleme
Biçim öğesi
Aynı dizine sahip öğeleri biçimlendirme

Denetim biçimlendirilmiş çıktı

Biçimlendirmeyi denetleme
Denetim aralığı
Hizalamayı denetleme
İntegral basamak sayısını denetleme
Ondalık ayırıcıdan sonraki basamak sayısını denetleme
Sonuç dizesine değişmez ayraçlar ekleme

Biçim dizelerini kültüre duyarlı hale getirme

Biçim dizelerini kültüre duyarlı hale getirme

Biçimlendirme işlemini özelleştirme

Özel biçimlendirme işlemi
Kesme noktası sağlayıcısı ve Roma rakamı biçimlendiricisi

String.Format yöntemini kullanmaya başlama

Bir nesnenin, değişkenin veya ifadenin değerini başka bir dizeye eklemeniz gerekiyorsa kullanın String.Format . Örneğin, bir Decimal değerin değerini bir dizeye ekleyerek kullanıcıya tek bir dize olarak görüntüleyebilirsiniz:

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.
let pricePerOunce = 17.36m
String.Format("The current price is {0} per ounce.", pricePerOunce)
|> printfn "%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.

Ayrıca bu değerin biçimlendirmesini denetleyebilirsiniz:

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.
let pricePerOunce = 17.36m
String.Format("The current price is {0:C2} per ounce.", pricePerOunce)
|> printfn "%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.

Biçimlendirmenin yanı sıra hizalamayı ve aralığı da denetleyebilirsiniz.

Dize ekleme

String.Format bir biçim dizesiyle başlar ve ardından dizelere dönüştürülecek ve biçim dizesinde belirtilen bir yere eklenecek bir veya daha fazla nesne veya ifade içerir. Örneğin:

decimal temp = 20.4m;
string s = String.Format("The temperature is {0}°C.", temp);
Console.WriteLine(s);
// Displays 'The temperature is 20.4°C.'
let temp = 20.4m
String.Format("The temperature is {0}°C.", temp)
|> printfn "%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} biçim dizesindeki bir biçim öğesidir. 0 , dize değeri bu konuma eklenecek nesnenin dizinidir. (Dizinler 0'da başlar.) Eklenecek nesne bir dize değilse, ToString sonuç dizesine eklemeden önce bir nesneye dönüştürmek için yöntemi çağrılır.

Burada, nesne listesinde iki biçim öğesi ve iki nesne kullanan başka bir örnek verilmiştir:

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.'
String.Format("At {0}, the temperature is {1}°C.", DateTime.Now, 20.4)
|> printfn "%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.'

Her biçim öğesinin dizininde nesne listesinde eşleşen bir nesne olduğu sürece nesne listesinde istediğiniz kadar biçim öğesi ve nesne olabilir. Ayrıca hangi aşırı yüklemeyi çağırdığınız konusunda da endişelenmeniz gerekmez; derleyicisi sizin için uygun olanı seçer.

Biçimlendirmeyi denetleme

Bir nesnenin nasıl biçimlendirildiğini denetlemek için bir biçim dizesi içeren bir biçim öğesinde dizini izleyebilirsiniz. Örneğin, {0:d} "d" biçim dizesini nesne listesindeki ilk nesneye uygular. Tek bir nesne ve iki biçim öğesi içeren bir örnek aşağıda verilmiştir:

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'
String.Format("It is now {0:d} at {0:t}", DateTime.Now)
|> printfn "%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'

Bir dizi tür, tüm sayısal türler (hem standarthem de özel biçim dizeleri), tüm tarih ve saatler (hem standarthem de özel biçim dizeleri) ve zaman aralıkları (hem standarthem de özel biçim dizeleri), tüm numaralandırma türleri numaralandırma türleri ve GUID'ler dahil olmak üzere biçim dizelerini destekler. Kendi türlerinize biçim dizeleri için destek de ekleyebilirsiniz.

Denetim aralığı

12 karakterlik bir dize ekleyen gibi {0,12}bir söz dizimi kullanarak sonuç dizesine eklenen dizenin genişliğini tanımlayabilirsiniz. Bu durumda, ilk nesnenin dize gösterimi 12 karakterlik alanda sağa hizalanır. (İlk nesnenin dize gösterimi 12 karakterden uzunsa, tercih edilen alan genişliği yoksayılır ve dizenin tamamı sonuç dizesine eklenir.)

Aşağıdaki örnek, "Year" dizesini ve bazı yıl dizelerini tutan 6 karakterlik bir alanın yanı sıra "Population" dizesini ve bazı popülasyon verilerini tutan 15 karakterlik bir alanı tanımlar. Karakterlerin alanda sağa hizalandığını unutmayın.

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
open System
open System.Text
 
let years = [| 2013; 2014; 2015 |]
let population = [| 1025632; 1105967; 1148203 |]
let sb = StringBuilder()
sb.Append(String.Format("{0,6} {1,15}\n\n", "Year", "Population")) |> ignore
for i = 0 to years.Length - 1 do
   sb.Append(String.Format("{0,6} {1,15:N0}\n", years[i], population[i])) |> ignore

printfn $"{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

Hizalamayı denetleme

Varsayılan olarak, bir alan genişliği belirtirseniz, dizeler alanları içinde sağa hizalanır. Bir alandaki dizeleri sola hizalamak için, 12 karakter sola hizalanmış bir alan tanımlamak gibi {0,-12} , alan genişliğini negatif bir işaretle önyüze eklersiniz.

Aşağıdaki örnek, hem etiketleri hem de verileri sola hizalaması dışında öncekine benzer.

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
let years = [| 2013; 2014; 2015 |]
let population = [| 1025632; 1105967; 1148203 |]
let mutable s = String.Format("{0,-10} {1,-10}\n\n", "Year", "Population")
for i = 0 to years.Length - 1 do
    s <- s + String.Format("{0,-10} {1,-10:N0}\n", years[i], population[i])
printfn $"\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 bileşik biçimlendirme özelliğini kullanır. Daha fazla bilgi için bkz . Bileşik Biçimlendirme.

Hangi yöntemi çağırmalıyım?

Amaç Call
Geçerli kültürün kurallarını kullanarak bir veya daha fazla nesneyi biçimlendirin. Parametre provider içeren aşırı yüklemeler dışında, kalan Format aşırı yüklemeler bir parametre ve ardından bir String veya daha fazla nesne parametresi içerir. Bu nedenle, çağırmak istediğiniz aşırı yüklemeyi belirlemeniz Format gerekmez. Dil derleyiciniz, bağımsız değişken listenize göre parametresi olmayan provider aşırı yüklemeler arasından uygun aşırı yüklemeyi seçer. Örneğin, bağımsız değişken listenizde beş bağımsız değişken varsa, derleyici yöntemini çağırır Format(String, Object[]) .
Belirli bir kültürün kurallarını kullanarak bir veya daha fazla nesneyi biçimlendirin. Bir parametreyle provider başlayan her Format aşırı yüklemenin ardından bir parametre ve bir String veya daha fazla nesne parametresi eklenir. Bu nedenle, çağırmak istediğiniz aşırı Format yüklemeyi belirlemeniz gerekmez. Dil derleyiciniz, bağımsız değişken listenize göre parametresi provider olan aşırı yüklemeler arasından uygun aşırı yüklemeyi seçer. Örneğin, bağımsız değişken listenizde beş bağımsız değişken varsa, derleyici yöntemini çağırır Format(IFormatProvider, String, Object[]) .
Bir uygulama veya uygulama ile ICustomFormatter özel biçimlendirme IFormattable işlemi gerçekleştirin. Parametresi olan dört aşırı yüklemeden herhangi biri provider . Derleyici, bağımsız değişken listenize göre parametresi provider olan aşırı yüklemeler arasından uygun aşırı yüklemeyi seçer.

Kısaca Biçim yöntemi

Yönteminin Formather aşırı yüklemesi bileşik biçimlendirme özelliğini kullanarak bileşik biçim dizesinde biçim öğeleri olarak adlandırılan sıfır tabanlı dizinli yer tutucuları içerir. Çalışma zamanında, her biçim öğesi parametre listesindeki karşılık gelen bağımsız değişkenin dize gösterimiyle değiştirilir. Bağımsız değişkenin değeri ise null, biçim öğesi ile String.Emptydeğiştirilir. Örneğin, aşağıdaki yöntem çağrısı Format(String, Object, Object, Object) üç biçim öğesi içeren bir biçim dizesi, , {1}ve {2}ve üç öğe {0}içeren bir bağımsız değişken listesi içerir.

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.
open System

let dat = DateTime(2012, 1, 17, 9, 30, 0) 
let city = "Chicago"
let temp = -16
String.Format("At {0} in {1}, the temperature was {2} degrees.", dat, city, temp)
|> printfn "%s"
// 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.

Biçimlendirme öğesi

Biçim öğesi şu söz dizimine sahiptir:

{index[,alignment][:formatString]}

Köşeli ayraçlar isteğe bağlı öğeleri belirtir. Açma ve kapatma ayraçları gereklidir. (Biçim dizesine değişmez değer açma veya kapatma ayracı eklemek için bkz.Bileşik Biçimlendirme makalesindeki Kaçış Ayraçları bölümü.)

Örneğin, para birimi değerini biçimlendirmek için bir biçim öğesi şu şekilde görünebilir:

var value = String.Format("{0,-10:C}", 126347.89m);
Console.WriteLine(value);
open System

String.Format("{0,-10:C}", 126347.89m)         
|> printfn "%s"
String.Format("{0,-10:C}", 126347.89D)

Biçim öğesi aşağıdaki öğelere sahiptir:

Dizin
Dize gösterimi dizede bu konuma dahil edilecek bağımsız değişkenin sıfır tabanlı dizini. Bu bağımsız değişken ise null, dizeye bu konuma boş bir dize eklenir.

Hizalama
isteğe bağlı. Bağımsız değişkenin eklendiği alanın toplam uzunluğunu ve sağ hizalı (pozitif tamsayı) veya sola hizalanmış (negatif tamsayı) olduğunu belirten imzalı tamsayı. Hizalamayı atlarsanız, karşılık gelen bağımsız değişkenin dize gösterimi önünde veya sonunda boşluk olmayan bir alana eklenir.

Hizalama değeri eklenecek bağımsız değişkenin uzunluğundan küçükse hizalama yoksayılır ve alan genişliği olarak bağımsız değişkenin dize gösteriminin uzunluğu kullanılır.

Formatstring
isteğe bağlı. Karşılık gelen bağımsız değişkenin sonuç dizesinin biçimini belirten dize. formatString'i atlarsanız, dize gösterimini oluşturmak için karşılık gelen bağımsız değişkenin parametresiz ToString yöntemi çağrılır. formatString belirtirseniz, biçim öğesi tarafından başvuruda bulunan bağımsız değişkenin arabirimi uygulaması IFormattable gerekir. Biçim dizelerini destekleyen türler şunlardır:

Ancak, herhangi bir özel türün var olan bir türün IFormattable uygulamasını uygulayabileceğini IFormattable veya genişletebileceğini unutmayın.

Aşağıdaki örnek, biçimlendirilmiş çıkış oluşturmak için ve formatString bağımsız değişkenlerini kullanıralignment.

// 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 %
// Create a list of 5-tuples with population data for three U.S. cities, 1940-1950.
let cities = 
    [ "Los Angeles", DateTime(1940, 1, 1), 1504277, DateTime(1950, 1, 1), 1970358
      "New York", DateTime(1940, 1, 1), 7454995, DateTime(1950, 1, 1), 7891957
      "Chicago", DateTime(1940, 1, 1), 3396808, DateTime(1950, 1, 1), 3620962
      "Detroit", DateTime(1940, 1, 1), 1623452, DateTime(1950, 1, 1), 1849568 ]

// Display header
String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n", "City", "Year", "Population", "Change (%)")
|> printfn "%s"

for name, year1, pop1, year2, pop2 in cities do
    String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
                  name, year1, pop1, year2, pop2,
                  double (pop2 - pop1) / double pop1)
    |> printfn "%s"
// 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 Example3
    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 %

Bağımsız değişkenlerin nasıl biçimlendirildiği

Biçim öğeleri dizenin başından itibaren sıralı olarak işlenir. Her biçim öğesinin, yöntemin bağımsız değişken listesindeki bir nesneye karşılık gelen bir dizini vardır. yöntemi bağımsız Format değişkenini alır ve dize gösterimini aşağıdaki gibi türetir:

Yöntemine ICustomFormatter.Format çağrıları kesen ve bileşik biçim dizesindeki her biçim öğesi için bir biçimlendirme yöntemine hangi bilgileri Format geçtiğini görmenizi sağlayan bir örnek için bkz . Örnek: Kesme noktası sağlayıcısı ve Roma rakamı biçimlendiricisi.

Daha fazla bilgi için bkz . Sipariş işleme.

Aynı dizine sahip biçim öğeleri

Yöntem, Format bir FormatException dizin öğesinin dizini bağımsız değişken listesindeki bağımsız değişken sayısından büyük veya buna eşitse bir özel durum oluşturur. Ancak, format birden çok biçim öğesi aynı dizine sahip olduğu sürece bağımsız değişkenlerden daha fazla biçim öğesi içerebilir. Aşağıdaki örnekte yöntemine Format(String, Object) yapılan çağrıda bağımsız değişken listesinin tek bir bağımsız değişkeni vardır, ancak biçim dizesi iki biçim öğesi içerir: biri sayının ondalık değerini, diğeri ise onaltılık değerini görüntüler.

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
open System

let values= [| Int16.MinValue; -27s; 0s; 1042s; Int16.MaxValue |]
printfn "%10s  %10s\n" "Decimal" "Hex"
for value in values do
    String.Format("{0,10:G}: {0,10:X}", value)
    |> printfn "%s"
// The example displays the following output:
//       Decimal         Hex
//    
//        -32768:       8000
//           -27:       FFE5
//             0:          0
//          1042:        412
//         32767:       7FFF
Module Example1
    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

Biçim ve kültür

Genellikle, bağımsız değişken listesindeki nesneler, özelliği tarafından CultureInfo.CurrentCulture döndürülen geçerli kültürün kuralları kullanılarak dize gösterimlerine dönüştürülür. Parametresini içeren provider aşırı yüklemelerinden Format birini çağırarak bu davranışı denetleyebilirsiniz. provider parametresi, biçimlendirme işleminin denetlenmesi için kullanılan özel ve kültüre özgü biçimlendirme bilgileri sağlayan bir IFormatProvider uygulamadır.

Arabirim IFormatProvider , GetFormatbiçimlendirme bilgileri sağlayan nesneyi döndürmekten sorumlu olan tek bir üyesine sahiptir. .NET'in kültüre özgü biçimlendirme sağlayan üç IFormatProvider uygulaması vardır:

Özel biçimlendirme işlemleri

Ayrıca, özel biçimlendirme işlemleri gerçekleştirmek için türü parametresine sahip provider yöntemin aşırı yüklemelerinden FormatIFormatProvider herhangi birini çağırabilirsiniz. Örneğin, bir tamsayıyı kimlik numarası veya telefon numarası olarak biçimlendirebilirsiniz. Özel biçimlendirme gerçekleştirmek için bağımsız değişkeninizin provider hem hem ICustomFormatter de IFormatProvider arabirimlerini uygulaması gerekir. yöntemi bağımsız Format değişken olarak bir ICustomFormatter uygulama geçirildiğinde provider , Format yöntemi uygulamasını IFormatProvider.GetFormat çağırır ve türünde ICustomFormatterbir nesne istemektedir. Ardından döndürülen ICustomFormatter nesnenin Format yöntemini çağırarak kendisine geçirilen bileşik dizedeki her biçim öğesini biçimlendirin.

Özel biçimlendirme çözümleri sağlama hakkında daha fazla bilgi için bkz . Nasıl yapılır: Özel Sayısal Biçim Sağlayıcılarını Tanımlama ve Kullanma ve ICustomFormatter. Tamsayıları biçimlendirilmiş özel sayılara dönüştüren bir örnek için bkz . Örnek: Özel biçimlendirme işlemi. İşaretsiz baytları Romen rakamlarına dönüştüren bir örnek için bkz . Örnek: Kesme noktası sağlayıcısı ve Roma rakamı biçimlendiricisi.

Örnek: Özel biçimlendirme işlemi

Bu örnek, x-xxxxx-xx biçiminde bir tamsayı değerini müşteri hesap numarası olarak biçimlendiren bir biçim sağlayıcısı tanımlar.

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.
open System

type CustomerFormatter() = 
    interface IFormatProvider with
        member this.GetFormat(formatType) =
            if formatType = typeof<ICustomFormatter> then
                this
            else
                null

    interface ICustomFormatter with
        member this.Format(format, arg, formatProvider: IFormatProvider) = 
            if this.Equals formatProvider |> not then
                null
            else
                let format = 
                    if String.IsNullOrEmpty format then "G"
                    else format.ToUpper()
                
                let customerString = 
                    let s = string arg
                    if s.Length < 8 then
                        s.PadLeft(8, '0')
                    else s
                
                match format with
                | "G" ->
                    customerString.Substring(0, 1) + "-" +
                        customerString.Substring(1, 5) + "-" +
                        customerString.Substring 6
                | "S" ->                          
                    customerString.Substring(0, 1) + "/" +
                        customerString.Substring(1, 5) + "/" +
                        customerString.Substring 6
                | "P" ->                          
                    customerString.Substring(0, 1) + "." +
                        customerString.Substring(1, 5) + "." +
                        customerString.Substring 6
                | _ ->
                    raise (FormatException $"The '{format}' format specifier is not supported.")

let acctNumber = 79203159
String.Format(CustomerFormatter(), "{0}", acctNumber)
|> printfn "%s"
String.Format(CustomerFormatter(), "{0:G}", acctNumber)
|> printfn "%s"
String.Format(CustomerFormatter(), "{0:S}", acctNumber)
|> printfn "%s"
String.Format(CustomerFormatter(), "{0:P}", acctNumber)
|> printfn "%s"
try
    String.Format(CustomerFormatter(), "{0:X}", acctNumber)
    |> printfn "%s"
with :? FormatException as e ->
    printfn $"{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.
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.

Örnek: Kesme noktası sağlayıcısı ve Roma rakamı biçimlendiricisi

Bu örnek, iki şey yapmak için ve IFormatProvider arabirimlerini uygulayan ICustomFormatter özel bir biçim sağlayıcısı tanımlar:

  • Uygulamasına ICustomFormatter.Format geçirilen parametreleri görüntüler. Bu, yöntemin Format(IFormatProvider, String, Object[]) biçimlendirmeye çalıştığı her nesne için özel biçimlendirme uygulamasına hangi parametreleri geçirdiğini görmemizi sağlar. Bu, uygulamanızda hata ayıklarken yararlı olabilir.

  • Biçimlendirilecek nesne "R" standart biçim dizesi kullanılarak biçimlendirilecek imzasız bir bayt değeriyse, özel biçimlendirici sayısal değeri Roma rakamı olarak biçimlendirir.

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
open System
open System.Globalization

type InterceptProvider() =
    interface IFormatProvider with
        member this.GetFormat(formatType) =
            if formatType = typeof<ICustomFormatter> then
                this
            else
                null
    interface ICustomFormatter with
        member _.Format(format, obj, provider: IFormatProvider) = 
            // Display information about method call.
            let formatString =
                if format = null then "<null>" else format
            printfn $"Provider: {provider.GetType().Name}, Object: %A{obj}, Format String: %s{formatString}"
                                
            if obj = null then
                String.Empty
            else
                // If this is a byte and the "R" format string, format it with Roman numerals.
                match obj with
                | :? byte as value when formatString.ToUpper().Equals "R" -> 
                    let mutable returnString = String.Empty

                    // Get the hundreds digit(s)
                    let struct (result, remainder) = Math.DivRem(value, 100uy)
                    if result > 0uy then
                        returnString <- String('C', int result)
                    let value = byte remainder
                    // Get the 50s digit
                    let struct (result, remainder) = Math.DivRem(value, 50uy)
                    if result = 1uy then
                        returnString <- returnString + "L"
                    let value = byte remainder
                    // Get the tens digit.
                    let struct (result, remainder) = Math.DivRem(value, 10uy)
                    if result > 0uy then
                        returnString <- returnString + String('X', int result)
                    let value = byte remainder 
                    // Get the fives digit.
                    let struct (result, remainder) = Math.DivRem(value, 5uy)
                    if result > 0uy then
                        returnString <- returnString + "V"
                    let value = byte remainder
                    // Add the ones digit.
                    if remainder > 0uy then 
                        returnString <- returnString + String('I', int remainder)
                    
                    // Check whether we have too many X characters.
                    let pos = returnString.IndexOf "XXXX"
                    if pos >= 0 then
                        let xPos = returnString.IndexOf "L" 
                        returnString <-
                            if xPos >= 0 && xPos = pos - 1 then
                                returnString.Replace("LXXXX", "XC")
                            else
                                returnString.Replace("XXXX", "XL")   
                    // Check whether we have too many I characters
                    let pos = returnString.IndexOf "IIII"
                    if pos >= 0 then
                        returnString <-
                            if returnString.IndexOf "V" >= 0 then
                                returnString.Replace("VIIII", "IX")
                            else
                                returnString.Replace("IIII", "IV")    
                    returnString 

                // Use default for all other formatting.
                | :? IFormattable as x ->
                    x.ToString(format, CultureInfo.CurrentCulture)
                | _ ->
                    string obj

let n = 10
let value = 16.935
let day = DateTime.Now
let provider = InterceptProvider()
String.Format(provider, "{0:N0}: {1:C2} on {2:d}\n", n, value, day)
|> printfn "%s"
String.Format(provider, "{0}: {1:F}\n", "Today: ", DateTime.Now.DayOfWeek)
|> printfn "%s"
String.Format(provider, "{0:X}, {1}, {2}\n", 2uy, 12uy, 199uy)
|> printfn "%s"
String.Format(provider, "{0:R}, {1:R}, {2:R}\n", 2uy, 12uy, 199uy)
|> printfn "%s"
// 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

SSS

Yönteme yapılan çağrılar üzerinden neden dize ilişkilendirmesi String.Format önerirsiniz?

Dize ilişkilendirmesi:

  • Daha esnek. Bileşik biçimlendirmeyi destekleyen bir yönteme çağrı gerektirmeden herhangi bir dizede kullanılabilir. Aksi takdirde yöntemini veya veya StringBuilder.AppendFormatgibi Console.WriteLine bileşik biçimlendirmeyi destekleyen başka bir yöntemi çağırmanız Format gerekir.

  • Daha okunabilir. Bir dizeye eklenecek ifade bağımsız değişken listesinde değil, ilişkilendirilmiş ifadede göründüğünden, ilişkilendirilmiş dizelerin kodlanıp okunması çok daha kolaydır. Daha yüksek okunabilirliklerinden dolayı, ilişkilendirilmiş dizeler yalnızca bileşik biçim yöntemlerine yapılan çağrıların yerini almakla kalmaz, aynı zamanda dize birleştirme işlemlerinde daha kısa ve daha net bir kod üretmek için de kullanılabilir.

Aşağıdaki iki kod örneğinin karşılaştırması, ilişkilendirilmiş dizelerin dize birleştirme ve bileşik biçimlendirme yöntemlerine çağrılar üzerindeki üstünlüğünü gösterir. Aşağıdaki örnekte birden çok dize birleştirme işleminin kullanılması ayrıntılı ve okunması zor kodlar oluşturur.

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.
open System

let names = [| "Balto"; "Vanya"; "Dakota"; "Samuel"; "Koani"; "Yiska"; "Yuma" |]
let output = 
    names[0] + ", " + names[1] + ", " + names[2] + ", " + 
    names[3] + ", " + names[4] + ", " + names[5] + ", " + 
    names[6] + "\n"

let date = DateTime.Now
output + String.Format("It is {0:t} on {0:d}. The day of the week is {1}.", date, date.DayOfWeek)
|> printfn "%s"
// 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 Example12
    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.

Buna karşılık, aşağıdaki örnekte ilişkilendirilmiş dizelerin kullanılması, dize birleştirme deyiminden ve önceki örnekteki yöntem çağrısından Format çok daha net ve daha kısa bir kod üretir.

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.
open System

let names = [| "Balto"; "Vanya"; "Dakota"; "Samuel"; "Koani"; "Yiska"; "Yuma" |]
let output = $"{names[0]}, {names[1]}, {names[2]}, {names[3]}, {names[4]}, {names[5]}, {names[6]}"  

let date = DateTime.Now
output + $"\nIt is {date:t} on {date:d}. The day of the week is {date.DayOfWeek}."
|> printfn "%s" 
// 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 Example13
    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.

Önceden tanımlanmış biçim dizelerini nerede bulabilirim?

Biçim öğelerinin yerini alan sonuç dizelerinin hizalamasını Nasıl yaparım? denetleyebilirsiniz?

Biçim öğesinin genel söz dizimi şöyledir:

{index[,alignment][: formatString]}

burada hizalama , alan genişliğini tanımlayan imzalı bir tamsayıdır. Bu değer negatifse, alandaki metin sola hizalanır. Pozitifse, metin sağa hizalanır.

Ondalık ayırıcıdan sonraki basamak sayısı Nasıl yaparım? denetlensin mi?

"D" (yalnızca tamsayılarla kullanılır), "G", "R" ve "X" dışındaki tüm standart sayısal biçim dizeleri , sonuç dizesindeki ondalık basamak sayısını tanımlayan bir duyarlık tanımlayıcısına izin verir. Aşağıdaki örnek, sonuç dizesindeki ondalık basamak sayısını denetlemek için standart sayısal biçim dizelerini kullanır.

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 %
open System

let values: obj list = [ 1603, 1794.68235, 15436.14 ]
for value in values do
   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.)
   |> printfn "%s"
// 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 Example7
    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 %

Özel sayısal biçim dizesi kullanıyorsanız, aşağıdaki örnekte gösterildiği gibi sonuç dizesindeki ondalık basamak sayısını denetlemek için "0" biçim tanımlayıcısını kullanın.

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
let value = 16309.5436m
String.Format("{0,12:#.00000} {0,12:0,000.00} {0,12:000.00#}", value)
|> printfn "%s"
// The example displays the following output:
//        16309.54360    16,309.54    16309.544
Module Example8
    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

İntegral basamak sayısını Nasıl yaparım? kontrol edin?

Varsayılan olarak, biçimlendirme işlemleri yalnızca sıfır olmayan tam sayı basamaklarını görüntüler. Tamsayıları biçimlendiriyorsanız, basamak sayısını denetlemek için "D" ve "X" standart biçim dizeleriyle bir duyarlık belirtici kullanabilirsiniz.

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
open System

let value = 1326
String.Format("{0,10:D6} {0,10:X8}", value)
|> printfn "%s"
// The example displays the following output:
//     001326   0000052E
Module Example10
    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

Aşağıdaki örnekte gösterildiği gibi, "0" özel sayısal biçim belirticisini kullanarak belirtilen sayıda tamsayı basamak içeren bir sonuç dizesi oluşturmak için bir tamsayıyı veya kayan noktalı sayıyı baştaki sıfırlarla sabitleyebilirsiniz.

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
open System

let value = 16342
String.Format("{0,18:00000000} {0,18:00000000.000} {0,18:000,0000,000.0}", value)
|> printfn "%s"
// The example displays the following output:
//           00016342       00016342.000    0,000,016,342.0
Module Example9
    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

Biçim listesine kaç öğe ekleyebilirim?

Pratik bir sınır yoktur. yönteminin Format(IFormatProvider, String, Object[]) ikinci parametresi, biçim listeniz olarak sınırlandırılmış liste veya nesne dizisi eklemenize olanak tanıyan özniteliğiyle ParamArrayAttribute etiketlenmiştir.

Sonuç dizesinde değişmez ayraçlar ("{" ve "}") Nasıl yaparım??

Örneğin, aşağıdaki yöntem çağrısının özel FormatException durum oluşturmasını nasıl engellersiniz?

result = String.Format("The text has {0} '{' characters and {1} '}' characters.",
                       nOpen, nClose);
let 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)

Tek bir açma veya kapatma ayracı her zaman biçim öğesinin başlangıcı veya sonu olarak yorumlanır. Kelimenin tam anlamıyla yorumlanması için kaçış olması gerekir. Aşağıdaki yöntem çağrısında olduğu gibi, "{" ve "}" yerine başka bir küme ayracı ("{{" ve "}}" ekleyerek küme ayracından kaçabilirsiniz:

string result;
int nOpen = 1;
int nClose = 2;
result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.",
                       nOpen, nClose);
Console.WriteLine(result);
let 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)

Ancak, kaçış ayraçları bile kolayca yanlış anlaşılır. Aşağıdaki örnekte gösterildiği gibi, küme ayraçlarını biçim listesine eklemenizi ve sonuç dizesine eklemek için biçim öğelerini kullanmanızı öneririz.

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);
let result =
    String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.", nOpen, "{", nClose, "}")
result = String.Format("The text has {0} '{1}' characters and {2} '{3}' characters.",
                 nOpen, "{", nClose, "}")

String.Format yöntemine çağrım neden formatexception oluşturur?

Özel durumun en yaygın nedeni, biçim öğesinin dizininin biçim listesindeki bir nesneye karşılık olmamasıdır. Bu durum genellikle biçim öğelerinin dizinlerini yanlış numaralandırdığınız veya biçim listesine bir nesne eklemeyi unuttuğunu gösterir. Sıralanmamış bir sol veya sağ küme ayracı karakteri dahil edilmeye çalışılırken de bir FormatExceptionoluşturur. Bazen, özel durum bir yazım hatasının sonucudur; örneğin, tipik bir hata "{" (sol ayraç) yerine "[" (sol köşeli ayraç) yanlış yazmaktır.

Format(System.IFormatProvider,System.String,System.Object[]) yöntemi parametre dizilerini destekliyorsa, dizi kullandığımda kodum neden özel durum oluşturur?

Örneğin, aşağıdaki kod bir FormatException özel durum oluşturur:

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);
open System

let rnd = Random()
let mutable total = 0
let numbers = Array.zeroCreate<int> 4
for i = 0 to 2 do
   let number = rnd.Next 1001
   numbers[i] <- number
   total <- total + number
numbers[3] <- total
Console.WriteLine("{0} + {1} + {2} = {3}", numbers)
Imports System.Collections.Generic

Module Example5
    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

Bu, derleyici aşırı yükleme çözümlemesi sorunudur. Derleyici bir tamsayı dizisini bir nesne dizisine dönüştüremediğinden, tamsayı dizisini tek bir bağımsız değişken olarak ele alır, bu nedenle yöntemini çağırır Format(String, Object) . Özel durum, biçim listesinde yalnızca tek bir öğe olan dört biçim öğesi olduğundan oluşturulur.

Visual Basic veya C# bir tamsayı dizisini nesne dizisine dönüştüremediğinden, yöntemini çağırmadan önce dönüştürmeyi Format(String, Object[]) kendiniz gerçekleştirmeniz gerekir. Aşağıdaki örnek bir uygulama sağlar.

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);
open System

let rnd = Random()
let numbers = Array.zeroCreate<int> 4
let mutable total = 0
for i = 0 to 2 do
   let number = rnd.Next 1001
   numbers[i] <- number
   total <- total + number
numbers[3] <- total
let values = Array.zeroCreate<obj> numbers.Length
numbers.CopyTo(values, 0)
Console.WriteLine("{0} + {1} + {2} = {3}", values)
Imports System.Collections.Generic

Module Example6
    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