C# 是否有一个.NET属性用于指定;显示名称";财产的所有权?
是否有一个属性允许您为类中的属性指定用户友好的名称 例如,假设我有以下课程:C# 是否有一个.NET属性用于指定;显示名称";财产的所有权?,c#,.net,properties,attributes,C#,.net,Properties,Attributes,是否有一个属性允许您为类中的属性指定用户友好的名称 例如,假设我有以下课程: public class Position { public string EmployeeName { get; set; } public ContactInfo EmployeeContactInfo { get; set; } } 我想指定EmployeeName属性的显示名称为“Employee name”,而EmployeeContactInfo属性的显示名称为“Employee Co
public class Position
{
public string EmployeeName { get; set; }
public ContactInfo EmployeeContactInfo { get; set; }
}
我想指定EmployeeName
属性的显示名称为“Employee name”,而EmployeeContactInfo
属性的显示名称为“Employee Contact Information”
编写自己的属性类非常简单,它允许我这样做:
[PropertyDisplayInfo(DisplayName = "Employee Name")]
public string EmployeeName { get; set; }
但是.NET中已经包含了类似的内容吗?是的,有
System.ComponentModel.DataAnnotations.DisplayAttribute
比实际上用于属性网格的DisplayNameAttribute
更好。现在.NET世界中有更多的组件将采用并使用DisplayAttribute
。它还有一些细节,如顺序
,组名
,短名
,以及在完成自动生成时是否显示属性(使用自动生成字段
)
DisplayAttribute
也是资源友好型的,是本地化的一个很好的选择。如果您想将其用于调试,您可能会感兴趣。在每个属性声明之前放置以下属性:
//[DisplayName("Your desired human readable field caption ")]
[DisplayName("ID")]
public int id {
get {return _id;}
set { SetField(ref _id, value, "id"); }
}
从.NET 4开始,有一个更好的属性System.ComponentModel.DataAnnotations.DisplayAttribute。为了方便其他人查找此答案,.NET 4.0中的Windows窗体DataGridView或PropertyGrid控件不支持System.ComponentModel.DataAnnotations.DisplayAttribute,因此,您可以重新使用System.ComponentModel.DisplayNameAttribute(如果您希望支持本地化,还可以编写自己的派生类)。