是否有用于指定属性"显示名称"的.NET属性?

Rob*_*rdy 11 .net c# attributes properties

是否有一个属性允许您为类中的属性指定用户友好名称?

例如,假设我有以下课程:

public class Position
{
     public string EmployeeName { get; set; }
     public ContactInfo EmployeeContactInfo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想指定EmployeeName属性的显示名称是"Employee Name",EmployeeContactInfo属性的显示名称是"Employee Contact Information".

编写我自己的属性类很容易,这样我就可以这样做:

[PropertyDisplayInfo(DisplayName = "Employee Name")]
public string EmployeeName { get; set; }
Run Code Online (Sandbox Code Playgroud)

但这样的东西已经包含在.NET中吗?

Tho*_*que 13

就在这里 System.ComponentModel.DisplayNameAttribute

  • 从.NET 4开始,有一个更好的属性,System.ComponentModel.DataAnnotations.DisplayAttribute (11认同)
  • 为了寻找此答案的其他人的利益,.NET 4.0中的Windows窗体DataGridView或PropertyGrid控件不支持System.ComponentModel.DataAnnotations.DisplayAttribute,因此您将回到使用System.ComponentModel.DisplayNameAttribute(并编写您的如果你想支持本地化,你自己的派生类. (5认同)

Mat*_*eer 12

System.ComponentModel.DataAnnotations.DisplayAttribute是一个更好的选择DisplayNameAttribute,实际上是用于财产网格.如今,.NET世界中的更多组件将会被使用和使用DisplayAttribute.它也有像细微Order,GroupName,ShortName以及是否在所有的时候自动生成完成(与显示属性AutoGenerateField).

DisplayAttribute 也是资源友好的,使其成为本地化的好选择.