2011-12-30 30 views
4

什麼是最好的方式來完成這樣的事情?將資源字符串格式化爲另一個?

假設我有以下一對Resource字符串。

BadRequestParameter:   Potential bad request aborted before execution. 
RequiredParameterConstraint: {0} parameter requires a value. {1} 

再假設我想設置{1}上第二個,到BadRequestParameter值。我可以很容易地使用string.Format來做到這一點。但是現在假設我有很多像Resource這樣的字符串,所有這些字符串都包含在其中。
什麼是最好的方式來編碼?在每種情況下都重複使用string.Format真的我可以做的所有事情?

更新

我會盡力解釋自己更好。這些都是資源字符串我其實有:

BadRequestParameter  Potential bad request aborted before execution. 
EmptyVector    Vectorized requests require at least one element. {0} 
OverflownVector   Vectorized requests can take at most one hundred elements. {0} 
RequiredParamConstraint {0} parameter requires a value. {1} 
SortMinMaxConstraint {0} parameter value '{1}' does not allow Min or Max parameters in this query. {2} 
SortRangeTypeConstraint Expected {0} parameter Type '{1}'. Actual: '{2}'. {3} 
SortValueConstraint  {0} parameter does not allow '{1}' as a value in this query. {2} 

我想避免在每個那些行結束寫入BadRequestParameter的字符串。因此,我在這些字符串的末尾添加了一個格式。現在的問題是,我想以某種方式自動參考{x}BadRequestParameter,爲了避免使像

string.Format(Error.EmptyVector, Error.BadRequestParameter); 

回答

1

我有很多的資源串喜歡第二個,所有這些都包括在其中的一些其他資源字符串。

除了存儲預製格式字符串以備使用之外,您可以存儲用於構建實際格式字符串的原材料,並添加代碼以在使用前以語法方式擴展它們。例如,你可以存儲的字符串是這樣的:

BadRequestParameter:   Potential bad request aborted before execution. 
SupportNumber:     (123)456-7890 
CallTechSupport:    You need to call technical support at {SupportNumber}. 
RequiredParameterConstraint: {{0}} parameter requires a value. {BadRequestParameter} {CallTechSupport} 

當然這些傳遞字符串string.Format作爲-是不會工作。您需要解析這些字符串,例如RegExp s,然後查找所有在大括號之間有單詞的實例,而不是數字。然後,您可以用每個單詞的序列號替換每個單詞,並根據在大括號之間找到的名稱生成一個參數數組。在這種情況下,你會得到這兩個值(僞):

formatString = "{{0}} parameter requires a value. {0} {1}"; 
// You replaced {BadRequestParameter} with {0} and {CallTechSupport} with {1} 
parameters = { 
    "Potential bad request aborted before execution." 
, "You need to call technical support at (123)456-7890." 
}; 

注:當然,生產這種陣列parameters需要遞歸。

在這一點上,你可以調用string.Format產生最終的字符串:

var res = string.Format(formatString, parameters); 

這將返回具有資源字符串前更換,對您的呼叫字符串:

"{0} parameter requires a value. Potential bad request aborted before execution. You need to call technical support at (123)456-7890." 

的呼叫者可以現在使用這個字符串進行格式化,而不用打擾其他資源值。

0

是:-),除非你想一個輔助方法是縮短通話,但是這真的僅僅是爲了方便起見

public static string f(string format, params object[] p) 
{ 
    return string.Format(format, p); 
} 
+0

-1:對我來說這是一個壞主意和臭味。 – 2011-12-30 15:30:13

+1

我確實使用'.FormatWith()'擴展方法,用於糖,但除了問題之外。 – bevacqua 2011-12-30 15:52:45

+0

這有什麼不好?我可以同意這個小小的價值,但如果他不想輸入5個字母,那就是他的業務。 – 2011-12-30 15:53:16

0

如果你把參數指標{#}作爲通配符那麼它爲什麼會讓你感覺預填他們的資源內。

我看絕對沒有錯

String.Format(RequiredParamterConstraint, "something", BadRequestParameter); 
+0

因爲我會重複自己很多,所以有十幾個資源將'BadRequestParameter'作爲格式參數,這也可能會引入錯誤(必須手動定位參數,而不是自動應用它)。 – bevacqua 2011-12-30 15:38:58

+0

這是string.format和資源的重點。我不明白它會如何引入更多的錯誤,而不是複雜的邏輯來爲你做這件事。 – msarchet 2011-12-30 15:46:24

相關問題