c# - 将资源字符串格式化为另一个?

标签 c# resources

完成这样的事情的最佳方法是什么?

假设我有以下一对 Resource 字符串。

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

假设我想将第二个上的 {1} 设置为 BadRequestParameter 的值。我可以使用 string.Format 轻松做到这一点。但是现在假设我有很多 Resource 字符串,就像第二个一样,所有这些字符串中都包含一些其他 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);

最佳答案

I have lots of Resource strings like the second one, all of which include some other Resource string in them.

您可以存储用于构建真实格式字符串的原始 Material ,并添加代码以在使用前以编程方式扩展它们,而不是存储准备使用的预制格式字符串。例如,您可以像这样存储字符串:

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 是行不通的。您需要解析这些字符串,例如使用 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."

调用者现在可以使用此字符串进行格式化,而无需担心其他资源值。

关于c# - 将资源字符串格式化为另一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8680971/

相关文章:

javascript - 用于改进向 MVC3 Razor 页面添加 css 和脚本资源的工具/加速器

java - 无法从其他项目找到字符串资源

c# - 有没有一种方法可以根据特定规则自动重新发送 Outlook 2007 和 MS Exchange 的电子邮件?

android - 自动从 strings.xml 中删除未引用的字符串

java - Scene.getStylesheets().add() 在 jar 文件中不起作用

c# - WCF - 检测响应中的错误

java - Java 中的资源加载无法正常工作

c# - 使用 Func 委托(delegate)重载解决方法中的 lambda 的 Visual Studio 错误?

c# 将 keydown 从表单传递到用户控件

c# - 从 AppDomain.AssemblyLoad 事件中抛出异常