【问题标题】:c# Custom Attribute with support for string resources does not load localized resources支持字符串资源的c#自定义属性不加载本地化资源
【发布时间】:2016-01-11 06:51:49
【问题描述】:

我有一个包含此自定义属性的 DLL

[AttributeUsage(AttributeTargets.Class)]
public class MyAttribute: System.Attribute {

private ResourceManager resManager = null;

public MyAttribute() {
}

public Type ResourceType { get; set; }

private string caption = string.Empty;
public string Caption {
  get { return getResourceString(caption); }
  set { caption = value; }
} //Caption

private string getResourceString(string resourceKey) {

  if (string.IsNullOrWhiteSpace(resourceKey))
    return string.Empty;

  if (ResourceType == default(Type))
    return resourceKey;

  if (resManager == null)
    resManager = new ResourceManager(ResourceType);

  return resManager.GetString(resourceKey) ?? string.Format("[[{0}]]", resourceKey);

} //getResourceString()

}

还有一个程序 (exe),它使用 MyAttribute 并且在 Resources.resxResources.fr.resx中具有英语和法语所需的资源 (resKeyHello) > 分别

[MyAttribute(Caption="resKeyHello", ResourceType=typeof(Resources)]
public Foo() {
}

问题是它从不使用法国卫星组件。我也尝试像 ResourceManager(ResourceType.FullName, ResourceType.Assembly) 那样创建 ResourceManager,但没有任何效果。并且还尝试像这样加载资源 resManager.GetString(resourceKey, Thread.CurrentThread.CurrentUICulture)

我可以在调试器中看到 CurrentUICulture 是法语。

【问题讨论】:

  • 对我来说,以这种方式在属性中使用逻辑是一个糟糕的设计选择。属性只是元数据。
  • @Matias,那么您如何本地化您的属性?是不是 Entity Framework 本地化验证属性的方式?
  • 实际调用您的 Caption 方法的代码中可能存在错误 - 显示此时连同 CurrentUICulture 的名称可能会有所帮助...
  • @DonaldLeclerc 我不知道该怎么做,但是应该在代码中使用属性来执行决策,而不是在属性本身中进行决策。
  • @MatíasFidemraizer,谢谢,我知道了。所以我将代码从 CustomAttribute 移到了使用它的 Method 中。不幸的是,我仍然遇到同样的问题。

标签: c# custom-attributes


【解决方案1】:

我终于找到了解决方法。

问题似乎与法语资源文件的生成方式有关。我使用了具有相同名称和 .fr.resx 扩展名的项目 -> 新建 -> 资源文件。

satellite DLL 在编译期间生成在 ./bin/fr 子文件夹中,但运行时没有看到它。

最后我使用 CodePlex 的“ResX 资源管理器”来生成我的资源文件,现在一切正常

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多