将短语翻译与 String.Format 集成
我有一个英文短语,如下所示:“我有 {0} 只狗和 {1} 只猫”。在代码中,我用 String.Format 提供数据:
String.Format("I have {0} dogs and {1} cats", 1, 2)
所以输出是这样的:“我有 1 只狗和 2 只猫”。
我要解决的问题是“我有 {0} 只狗和 {1} 只猫”这句话需要翻译成其他语言。
在此西班牙语翻译示例中,英语短语“I have {0} dogs and {1} cats”和翻译短语“Tengo {0} perros y gatos {1}”存储在数据库中。
如果用户要将“Tengo {0} perros y gatos {1}”更改为“Tengo {0} perros y gatos {3}”,则当我调用 String.Format("Tengo {0 } perros y gatos {3}", 1, 2)。
现在我正在捕获格式异常,感觉不对。我正在寻找更好的解决方案的想法。
I have a phrase in English that looks like this: "I have {0} dogs and {1} cats". In code, I provide the data with a String.Format:
String.Format("I have {0} dogs and {1} cats", 1, 2)
So the output is this: "I have 1 dogs and 2 cats".
The problem that I'm trying to solve is the phrase "I have {0} dogs and {1} cats" needs to be translated in other languages.
In this Spanish translation example, the English phrase "I have {0} dogs and {1} cats" and the translated phrase "Tengo {0} perros y gatos {1}" are stored in a database.
If the user were to change "Tengo {0} perros y gatos {1}" to "Tengo {0} perros y gatos {3}", a System.FormatException will be thrown when I call String.Format("Tengo {0} perros y gatos {3}", 1, 2).
For now I'm trapping the format exception and it feels wrong. I'm looking for ideas on a better solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(6)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
在保存到数据库之前,为什么不看看 String.Format 是否抛出异常?如果是这样——不要让用户保存。
只需一个简单的想法就可以解决问题......
Before saving to the database, why not see if you String.Format throws? If so -- do not let the user save.
Just a simple idea that may solve the problem...