Cad*_*oux 6 .net string-formatting
在.NET之前,我们有自己的短语本地化系统,我们建立了一种方式,使注释嵌套在格式化字符串中,如:"{0:price}".随着岁月的流逝,我发现我越来越想念这个.
似乎没有办法在.NET中就地记录格式化字符串:
string.Format("{0//numerator} / {1//denominator} = {2//ratio}"
,somevar
,anothervar
,yetanothervar);
Run Code Online (Sandbox Code Playgroud)
特别是这在插入点被重新排序的本地化/用语中很有用,而不需要更改代码:
string.Format("Dividing {1//denominator} into {0//numerator} gives {2//ratio}"
,somevar
,anothervar
,yetanothervar);
Run Code Online (Sandbox Code Playgroud)
任何人都有任何技巧,他们用来记录这些,以避免在维护/本地化等条款重新安排时出错?
注释很重要的原因是,对于本地化和配置,通常,字符串不在包含变量的代码中 - 我已将它们放在资源文件,app.config和数据库中.
在一个实际的例子中,子类控件公开了PhraseID属性(控件被映射到从表单生成的XML文件中的ID,并且表单控件被动态翻译),因此子类表单执行如下操作:
// Handle the phrases without insertion points - this is in the base class
foreach (Control in this.Controls) {
IXLatable ixl = (IXLatable) Control;
ixl.Text = GetPhrase(ixl.PhraseID);
}
// in the individual form classes, they override the behavior for complex displays:
lnkPublish.Text = string.Format(GetPhrase(lnkPublish.PhraseID), filename, foldername, userid);
Run Code Online (Sandbox Code Playgroud)
字典包含默认和本地化字符串,如:
phraseid, language code, phrase
1,en,"{0//filename} published to {1//foldername} by {2//userid}"
1,pl,"{2//userid} ublishedpay ethay ilefay {0//filename} otay {1//foldername}"
Run Code Online (Sandbox Code Playgroud)
如果在默认短语中提供了注释,那么翻译者(从不看到源代码)会错误地索引错误的可能性要小得多.非本地化的演讲者更容易解决翻译资源中的问题.
你可以看看Phil Haack 的 NamedFormat 扩展,它允许你使用类似的格式
NamedFormat("{{{foo}}}", new {foo = 123})
Run Code Online (Sandbox Code Playgroud)