[英]String.Format() - Repassing params but adding more parameters
我想做那樣的事情:
public string GetMessage(params object otherValues[]) {
return String.Format(this.Message, this.FirstValue, otherValues);
}
所以,我想將一系列參數傳遞給String.Format()
但是添加一個新參數。
什么是最好的方法,知道我們可以“重建”一個新的對象數組,這似乎並不好。
public string GetMessage(params object[] otherValues)
{
return String.Format(this.Message, new[] { this.FirstValue }.Concat(otherValues).ToArray<object>());
}
如果通常很少有other
參數,我會使用現有的重載:
public string GetMessage(params object[] otherValues) {
if (otherValues == null) return string.Format(this.Message, this.FirstValue);
switch (otherValues.Length)
{
case 0:
return string.Format(this.Message, this.FirstValue);
case 1:
return string.Format(this.Message, this.FirstValue, otherValues[0]);
case 2:
return string.Format(this.Message, this.FirstValue, otherValues[0], otherValues[1]);
default:
return string.Format(this.Message, new[] { this.FirstValue }.Concat(otherValues).ToArray());
}
}
如果您不希望在每個GetMessage(...)調用中創建新數組,則可以在開頭一次 將FirstValue插入到Message中。 然后GetMessage(...)只使用string.Format(...)的otherValues參數。
設置FirstValue后, Message屬性初始化一次,例如在構造函數或init方法中,如下所示:
void InitMessage()
{
Message = String.Format(Message, FirstValue, "{0}", "{1}", "{2}", "{3}", "{4}");
}
該方法InitMessage初始化與FirstValue在消息第一索引和索引的與休息“{}指數”,即“{0}”,“{1}”,“{2}”,...(它被允許具有比消息索引更多的params
元素。
現在GetMessage可以調用String.Format而不需要像這樣的任何數組操作:
public string GetMessage(params object[] otherValues)
{
return String.Format(Message, otherValues);
}
假設以下屬性值:
this.Message = "First value is '{0}'. Other values are '{1}' and '{2}'."
和this.FirstValue = "blue"
。
InitMessage將消息更改為:
"First value is 'blue'. Other values are '{0}' and '{1}'."
。
GetMessage調用
GetMessage("green", "red")
結果是
"First value is 'blue'. Other values are 'green' and 'red'."
。
如果你真的無法為數組創建另一個結構,那么另一個混亂的方法是使用RegEx破解格式化。
private string FormatEval(Match m)
{
int val = -1;
string formatted = m.Value;
if (int.TryParse(m.Groups["index"].Value, out val))
formatted = val == 0 ? this.FirstValue : "{" + (val - 1).ToString() + "}";
return formatted;
}
public string GetMessage(params object[] otherValues)
{
string format = Regex.Replace(this.Message, @"\{(?<index>\d+)\}", FormatEval);
return string.Format(format, otherValues);
}
基本上只是解析格式化標記({0},{1})等的格式字符串。並減少它們的索引。 如果令牌最初為{0},請將其替換為this.FirstName字符串。
基本上它正在做的是手動執行String.Format的第一步,然后將結果字符串傳遞給REAL String.Format方法來完成。
為了避免在everey GetMessage調用中創建數組,您可以通過其離散元素傳遞otherValues :
public string GetMessage(params object[] otherValues)
{
return String.Format(Message,
FirstValue,
GetOrDefault(otherValues, 0),
GetOrDefault(otherValues, 1),
GetOrDefault(otherValues, 2),
GetOrDefault(otherValues, 3),
GetOrDefault(otherValues, 4));
}
private object GetOrDefault(object[] otherValues, int index)
{
if (otherValues == null)
return null;
if (index < otherValues.Length)
return otherValues[index];
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.