[英]String formatting in C#
我正在通過字符串格式化“備忘單”工作,這樣我就可以看到不同的字符串格式化參數如何影響字符串輸出。 在使用DateTime
字符串格式化參數時,我寫了這個小測試:
char[] dtFormats = new char[] { 'd', 'D', 'f', 'F', 'g', 'G', 'm', 'o', 'r', 's', 't', 'T', 'u', 'U', 'y' };
foreach (char format in dtFormats)
{
Console.WriteLine("DateTime format {0} = {1:" + format + "}", format, DateTime.Now);
}
它所做的就是使用每個參數顯示DateTime
所有不同格式。
除此之外,我想專注於此:
Console.WriteLine("DateTime format {0} = {1:" + format + "}", format, DateTime.Now);
現在我知道{0}
被格式(參數0)替換, {1:?}
被DateTime.Now
(參數1)替換。
我試着像這樣重寫這個:
Console.WriteLine("DateTime format {0} = {1:{0}}", format, DateTime.Now);
這引發了一個FormatException
,但我想知道為什么你不能將字符串占位符嵌套在其他格式字符串占位符中。
在這種情況下,它應該使用format參數替換{0}
,使用DateTime.Now
替換{0}
{1:{0}}
,然后使用冒號和format參數。
這在C#中是不可能的嗎?
編輯:
就此而言,為什么Console.WriteLine("{{0}}", "Hello World");
導致"{0}"
而不是"{Hello World}"
?
我們如何簡化這一點呢? 當語法聲明{{
表示單個文字{
時,您正試圖嵌套大括號。 這就是你要找的東西:
Console.WriteLine("DateTime format {0} = {1}", format, DateTime.Now.ToString(format));
並回答這個問題:
就此而言,為什么Console.WriteLine(“{{0}}”,“Hello World”); 導致“{0}”而不是“{Hello World}”?
我重申{{
,在語法上意味着單個字面{
。
現在,如果你想使用冒號語法,那么無論如何你都有錯誤,就像這個{100:C}
,它會以貨幣格式顯示100
。 但是你真的不需要在這里這樣做,因為要使這種格式工作很困難,因為你需要這個{1:{0}}
並且因為轉義語法而失敗。
它不起作用,因為雙卷曲}}
轉義格式化字符串中的花括號。
如你所見,這個:
string.Format("This {{is}} my {{escaped}} curlies");
..很好(導致This {is} my {escaped} curlies)
..因為它們被轉義了。 如果你像你一樣嵌套它們......解析器將不知道是否逃脫。
圖像是解析器並遇到此問題:
Console.WriteLine("DateTime format {0} = {1:{0}}", format, DateTime.Now);
/* ^^ Okay, I'll escape this. WAIT!
.. now I have a two single
curly open braces. This is
a badly formatted format string
now.. FormatException!*/
您可以嘗試以下方法:
Console.WriteLine(string.Format("DateTime format {0} = {{1:{0}}}", format), format, DateTime.Now);
在格式內你不能引用任何參數。
一個簡單的程序,以確保你不會有任何問題,因為字符被誤解是分開放在每一邊的東西:左邊,只是對可能有最少附加信息的塊的引用; 對於右側,需要復雜的塊(不僅僅是變量)。 例:
Console.WriteLine("DateTime format {0}{1}{2}", format, " = {" + DateTime.Now, ":" + format + "}");
甚至:
Console.WriteLine("{0}{1}{2}", "DateTime format " + format, " = {" + DateTime.Now, ":" + format + "}");
你甚至可能依賴變量:
string chunk1 = "DateTime format " + format;
string chunk2 = " = {" + DateTime.Now;
string chunk3 = ":" + format + "}";
Console.WriteLine("{0}{1}{2}", chunk1, chunk2, chunk3);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.