不幸的是,您不能直接將翻譯文本提供給屬性,因爲屬性只能包含在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