支持字符串资源的c#自定义属性不会加载本地化资源
我有一个包含此自定义属性的DLL支持字符串资源的c#自定义属性不会加载本地化资源,c#,custom-attributes,C#,Custom Attributes,我有一个包含此自定义属性的DLL [AttributeUsage(AttributeTargets.Class)] public class MyAttribute: System.Attribute { private ResourceManager resManager = null; public MyAttribute() { } public Type ResourceType { get; set; } private string caption = string.Empt
[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() {
}
问题是它从未使用法国卫星组件。我还尝试像这样创建ResourceManagerResourceManager(ResourceType.FullName,ResourceType.Assembly),但没有任何效果。还尝试像这样加载资源resManager.GetString(resourceKey,Thread.CurrentThread.CurrentUICulture)
我可以在调试器中看到CurrentUICulture是法语。我终于找到了解决方法 问题似乎与法语资源文件的生成方式有关。我使用了具有相同名称和.fr.resx扩展名的Project->New->Resources文件 卫星DLL是在编译期间在./bin/fr子文件夹中生成的,但运行时没有看到它
最后,我使用CodePlex中的“ResX资源管理器”生成了我的资源文件,现在一切都正常了,以这种方式在属性中使用逻辑是一个糟糕的设计选择。属性只是元数据,那么如何本地化您的attibutes呢?实体框架不是本地化验证属性的方式吗?可能的错误是在实际调用
Caption
方法的代码中-显示与CurrentUICulture
的名称一起,在这一点上可能会有所帮助…@Donaldlecerc我不知道该怎么做,但是属性应该在代码中用来执行决策,而不是在属性本身中执行决策。@MatíasFidemraizer,thanx,我知道了。因此,我将代码从CustomAttribute移动到使用它的方法。不幸的是,我仍然遇到同样的问题。