簡體   English   中英

動態String.Format取決於params

[英]dynamic String.Format depending of params

給出以下示例:

string amountDisplay = presentation.Amount == 1 ? "" : String.Format("{0} x ", presentation.Amount);

無論如何使用String.Format所以它的格式取決於屬性,而不必做參數的'值'的條件?

另一個用例:

String.Format("({0}) {1}-{2}", countryCode, areaCode, phonenumber); 

如果我只有phonenumber,我最終會得到類似“()-5555555”的東西,這是不可取的。

另一個用例:

String.Format("my {0} has {1} cat[s]", "Aunt", 3) 

在這種情況下,如果值> 1,我想在[]中包含s。

是否有任何String.Format的黑色'語法'根據參數值刪除代碼部分或null?

謝謝。

並不是的。 你可以為復數[s]破解一些東西,當然,但它不是一個匹配所有用例的通用解決方案。

無論如何,您都應該檢查輸入的有效性。 如果您希望areaCode不為null,並且它是像string一樣的可空類型,請在方法的開頭進行一些檢查。 例如:

public string Foo(string countryCode, string areaCode, string phoneNumber)
{
    if (string.IsNullOrEmpty(countryCode)) throw new ArgumentNullException("countryCode");
    if (string.IsNullOrEmpty(areaCode)) throw new ArgumentNullException("areaCode");
    if (string.IsNullOrEmpty(phoneNumber)) throw new ArgumentNullException("phoneNumber");

    return string.Format(......);
}

在用戶的輸入上補償一些驗證錯誤不是UI的工作。 如果數據錯誤或丟失,請勿繼續。 這只會給你帶來奇怪的蟲子和許多痛苦。

您還可以嘗試PluralizationServices服務。 像這樣的東西:

using System.Data.Entity.Design.PluralizationServices;

string str = "my {0} has {1} {3}";
PluralizationService ps = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en-us"));
str = String.Format(str, "Aunt", value, (value > 1) ? ps.Pluralize("cat") : "cat");

嘗試使用條件運算符:

string str = "my {0} has {1} cat" + ((value > 1) ? "s" : "");

str = String.Format(str, "Aunt", value);

僅解決第二個問題,但是:

int x = 3;
String.Format("my {0} has {1} cat{2}", "Aunt", x, x > 1 ? "s" : ""); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM