C# 中的本地化属性参数
在 C# 中,属性参数必须是常量表达式、typeof 或数组创建表达式。
各种库(例如 Castle 验证器)允许指定将看似本地化的错误消息传递给属性构造函数:
//this works
[ValidateNonEmpty("Can not be empty")]
//this does not compile
[ValidateNonEmpty(Resources.NonEmptyValidationMessage)]
有什么方法可以解决此问题并本地化这些参数吗?
如果使用 Castle Validator 时没有解决此问题的方法,是否有类似于 Castle Validator 的验证库可以本地化验证消息?
编辑:我发现数据注释验证库如何解决这个问题。非常优雅的解决方案: http://haacked.com/archive/ 2009/12/07/本地化-aspnetmvc-validation.aspx
In C#, attribute parameters require to be a constant expression, typeof or array creation expression.
Various libraries, like for example Castle validator, allow specifying passing what seems like localized error messages to attribute constructor:
//this works
[ValidateNonEmpty("Can not be empty")]
//this does not compile
[ValidateNonEmpty(Resources.NonEmptyValidationMessage)]
Is there any way how to approach this problem and localize these arguments?
In case there is no workaround for this when using Castle Validator, is there a validation library similar to Castle Validator that allows localization of validation messages?
EDIT: I found how Data Annotations validation library approaches this problem. Very elegant solution: http://haacked.com/archive/2009/12/07/localizing-aspnetmvc-validation.aspx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我们也遇到了类似的问题,但与 Castle 无关。我们使用的解决方案只是定义一个从另一个属性派生的新属性,并使用常量字符串作为对资源管理器的查找,如果没有找到,则返回到键字符串本身。
用法类似于:
然后,每个特定于语言环境的资源文件都可以根据需要定义自己的
Entities.FruitBasket
条目。We had a similar issue, although not with Castle. The solution we used was simply to define a new attribute which was derived from the other one, and which used the constant string as a lookup to the resources manager, and fell back to the key string itself if none was found.
Usage is something like:
Then each locale-specific resource file can define its own
Entities.FruitBasket
entry, as needed.它开箱即用:
It works out of the box: