如果您只使用的Name
属性,DisplayAttribute
您可以通过继承 (older) 来实现这一点DisplayNameAttribute
,它不是密封的:
using System.Resources;
namespace System.ComponentModel
{
public class LocalisedDisplayNameAttribute
: DisplayNameAttribute
{
readonly ResourceManager m_resourceManager;
readonly string m_resourceName;
public LocalisedDisplayNameAttribute(ResourceManager resourceManager,
string resourceName)
: base()
{
m_resourceManager = resourceManager;
m_resourceName = resourceName;
}
public override string DisplayName
{
get { return m_resourceManager.GetString(m_resourceName); }
}
}
}
然后,您可以为常用字符串资源设置显示属性:
public class DisplayBizAttribute
: LocalisedDisplayNameAttribute
{
public DisplayBizAttribute(string resourceName)
: base(StringsBiz.ResourceManager, resourceName)
{
}
}
public class DisplayWebAttribute
: LocalisedDisplayNameAttribute
{
public DisplayBizAttribute(string resourceName)
: base(StringsWeb.ResourceManager, resourceName)
{
}
}
然后您可以使用字符串文字或常量非常轻松地本地化您的属性显示名称:
[DisplayBiz("ProductName")]
public string ProductName { get; set; }
[DisplayBiz(StringNames.PHONE_NUMBER)]
public string ProductName { get; set; }
[DisplayWeb("EmailAddress")]
public string EmailAddress { get; set; }
更新
这可以通过在每个属性类中声明一个枚举,并更改构造函数或添加一个新的来改进:
public class DisplayBizAttribute
: LocalisedDisplayNameAttribute
{
public enum Name
{
PhoneNumber,
ProductName,
}
public DisplayBizAttribute(Name resourceName)
: base(StringsBiz.ResourceManager, resourceName.ToString())
{
}
}
现在您不必使用硬编码字符串。
[DisplayBiz(DisplayBiz.Name.ProductName)]
public string ProductName { get; set; }
这是你经常做的事情,所以我想添加一个using
来缩短枚举:
using Biz = System.ComponentModel.DisplayBiz.Name;
...
[DisplayBiz(Biz.PhoneNumber)]
public string PhoneNumber { get; set; }