c# – 将资源字符串格式化为另一个?
完成这样的事情最好的方法是什么?
假设我有以下资源字符串对. BadRequestParameter: Potential bad request aborted before execution. RequiredParameterConstraint: {0} parameter requires a value. {1} 并且假设我想在第二个上设置{1}到BadRequestParameter的值.我可以使用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); 解决方法
您可以存储用于构建实际格式字符串的原始材料,并添加代码以在使用前以编程方式扩展它们,而不是存储准备好使用的预制格式字符串.例如,您可以存储如下字符串: 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 as-is是行不通的.您需要解析这些字符串,例如使用RegExps,并找到所有在花括号之间有单词的实例,而不是数字.然后,您可以用序列号替换每个单词,并根据花括号之间的名称生成一个参数数组.在这种情况下,您将获得这两个值(伪代码): 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." }; 注意:当然,生成这个参数数组需要递归. 此时,您可以调用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." 调用者现在可以使用此字符串进行格式化,而无需使用其他资源值. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |