我正在研究一个将被来自其他国家/地区的一些人使用的类(class)。我必须本地化每条消息,警告 e.c.以便他们能够理解我们的意思。在许多情况下,我实现了我的目标。但是这些像描述这样的属性属性实在是太让人头疼了。
这是我现在拥有的:
[Category("Editable Values"), Description("Sets the minimum select...")]
public Ampere Simin
{
get
{...}
set
{...}
}
和
[Category("Editable Values"), Description(Localisation.Simin)] // "Localisation" here is the internal resource file that i wrote for messages, warnings, exceptions and -unfortunately- descriptions
public Ampere Simin
{
get
{...}
set
{...}
}
这就是我想要做的。但是不可能以这种方式使用本地化。关于我可以用来代替它的东西有什么建议吗?
最佳答案
子类:
[STAThread]
static void Main()
{ // just some example code to show it working in winforms, but
// anything using System.ComponentModel should see the change
Application.EnableVisualStyles();
Application.Run(new Form {Controls = {new PropertyGrid {Dock = DockStyle.Fill, SelectedObject = new Foo()}}});
}
class Foo
{ // assume the following literals are keys, for example to a RESX
[LocalizedCategory("cat")]
[LocalizedDescription("desc")]
[LocalizedDisplayName("disp name")]
public string Bar { get; set; }
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter)]
class LocalizedDescriptionAttribute : DescriptionAttribute
{
static string Localize(string key)
{
// TODO: lookup from resx, perhaps with cache etc
return "Something for " + key;
}
public LocalizedDescriptionAttribute(string key)
: base(Localize(key))
{
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event)]
class LocalizedDisplayNameAttribute : DisplayNameAttribute
{
static string Localize(string key)
{
// TODO: lookup from resx, perhaps with cache etc
return "Something for " + key;
}
public LocalizedDisplayNameAttribute(string key)
: base(Localize(key))
{
}
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter)]
class LocalizedCategoryAttribute : CategoryAttribute
{
public LocalizedCategoryAttribute(string key) : base(key) { }
protected override string GetLocalizedString(string value)
{
// TODO: lookup from resx, perhaps with cache etc
return "Something for " + value;
}
}
关于c# - 如何在 C# 中本地化属性描述?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7398653/