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

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

假设我有以下资源字符串对.

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

并且假设我想在第二个上设置{1}到BadRequestParameter的值.我可以使用string.Format轻松地做到这一点.但现在假设我有许多资源字符串,如第二个,所有资源字符串都包含其中的一些其他资源字符串.
 编码的最佳方法是什么?在每种情况下使用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.

您可以存储用于构建实际格式字符串的原始材料,并添加代码以在使用前以编程方式扩展它们,而不是存储准备好使用的预制格式字符串.例如,您可以存储如下字符串:

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."

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

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...