不幸的是,您不能直接将翻译文本提供给属性,因为属性只能包含在compile time处已知的数据。因此,您需要提供一些编译时间常量值,稍后您可以使用它来查找翻译的测试。
一种解决方案是将资源名称传递给属性。然后,当您想要显示翻译文本时,您可以获取资源名称,查找资源中的文本并显示结果。
例如您的属性可能类似于:
[Export(Name = "SomeText")]
public class MyExport
{
}
然后,当你想显示你从定义导出组件加载资源字符串,你提取从加载资源的实际文本。例如像这样(从another answer借来的):
var assembly = typeof(MyExport).Assembly;
// Resource file.. namespace.ClassName
var rm = new ResourceManager("MyAssembly.Strings", assembly);
// exportName contains the text provided to the Name property
// of the Export attribute
var text = rm.GetString(exportName);
有关此解决方案的一个明显缺点是你失去了类型安全,您使用的Strings.SomeText属性来获取。
--------- ---------编辑
为了更容易一点,让你可以创建它接受ExportAttribute
的衍生物译文足够的信息来提取翻译的文本。例如自定义ExportAttribute
可能看起来像这样
public sealed class NamedExportAttribute : ExportAttribute
{
public NamedExportAttribute()
: base()
{
}
public string ResourceName
{
get;
set;
}
public Type ResourceType
{
get;
set;
}
public string ResourceText()
{
var rm = new ResourceManager(ResourceType);
return rm.GetString(ResourceName);
}
}
使用这个属性,你可以应用它这样
[NamedExport(
ResourceName = "SomeText",
ResourceType = typeof(MyNamespace.Properties.Resources))]
public sealed class MyClass
{
}
最后,当你需要得到翻译后的文本,你可以做到这一点
var attribute = typeof(MyClass).GetCustomAttribute<NamedExportAttribute>();
var text = attribute.ResourceText();
另一种选择是使用DisplayAttribute
仅供参考:我刚发现ME F 2支持我正在寻找的通用导入,但是您必须定位.NET Framework 4.5以利用此功能。 – Hannish