C#中的本地化属性参数

时间:2010-01-23 14:32:41

标签: c# validation localization attributes castle

在C#中,属性参数需要是常量表达式,typeof或数组创建表达式。

各种库,例如Castle验证器,允许指定将看似本地化的错误消息传递给属性构造函数:

//this works
[ValidateNonEmpty("Can not be empty")]

//this does not compile
[ValidateNonEmpty(Resources.NonEmptyValidationMessage)]

有没有办法解决这个问题并将这些参数本地化?

如果在使用Castle Validator时没有解决方法,是否有类似于Castle Validator的验证库,允许本地化验证消息?

编辑:我发现Data Annotations验证库如何解决这个问题。非常优雅的解决方案:http://haacked.com/archive/2009/12/07/localizing-aspnetmvc-validation.aspx

2 个答案:

答案 0 :(得分:4)

我们遇到了类似的问题,尽管没有Castle。我们使用的解决方案只是定义一个新属性,该属性派生自另一个属性,并使用常量字符串作为资源管理器的查找,如果没有找到则返回到密钥字符串本身。

[AttributeUsage(AttributeTargets.Class
  | AttributeTargets.Method
  | AttributeTargets.Property
  | AttributeTargets.Event)]
public class LocalizedIdentifierAttribute : ... {
  public LocalizedIdentifierAttribute(Type provider, string key)
    : base(...) {
    foreach (PropertyInfo p in provider.GetProperties(
      BindingFlags.Static | BindingFlags.NonPublic)) {
      if (p.PropertyType == typeof(System.Resources.ResourceManager)) {
        ResourceManager m = (ResourceManager) p.GetValue(null, null);

        // We found the key; use the value.
        return m.GetString(key);
      }
    }

    // We didn't find the key; use the key as the value.
    return key;
  }
}

用法类似于:

[LocalizedIdentifierAttribute(typeof(Resource), "Entities.FruitBasket")]
class FruitBasket {
  // ...
}

然后,每个特定于语言环境的资源文件都可以根据需要定义自己的Entities.FruitBasket条目。

答案 1 :(得分:0)

开箱即用:

    [ValidateNonEmpty(
        FriendlyNameKey = "CorrectlyLocalized.Description",
        ErrorMessageKey = "CorrectlyLocalized.DescriptionValidateNonEmpty",
        ResourceType = typeof (Messages)
        )]
    public string Description { get; set; }
相关问题