【发布时间】: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.resx 和 Resources.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