【问题标题】:Is there a .NET attribute for specifying the "display name" of a property?是否有用于指定属性“显示名称”的 .NET 属性?
【发布时间】:2011-04-04 13:36:18
【问题描述】:

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

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

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 中了吗?

【问题讨论】:

    标签: c# .net properties attributes


    【解决方案1】:

    【讨论】:

    • 从 .NET 4 开始,有一个更好的属性,System.ComponentModel.DataAnnotations.DisplayAttribute
    • 为了其他人在寻找这个答案的利益,System.ComponentModel.DataAnnotations.DisplayAttribute 不受 .NET 4.0 中的 Windows 窗体 DataGridView 或 PropertyGrid 控件的支持,因此您可以重新使用 System .ComponentModel.DisplayNameAttribute(如果您想支持本地化,还可以编写自己的派生类)。
    【解决方案2】:

    System.ComponentModel.DataAnnotations.DisplayAttribute 是比DisplayNameAttribute 更好的选择,DisplayNameAttribute 实际上是用于属性网格。如今,.NET 世界中的更多组件将采用并使用DisplayAttribute。它还具有Order、GroupName、ShortName 等细节,以及在自动生成完成时是否显示属性(使用AutoGenerateField)。

    DisplayAttribute 还资源友好,是本地化的不错选择。

    【讨论】:

      【解决方案3】:

      如果你想用这个来调试,你可能对DebuggerDisplayAttribute感兴趣。

      【讨论】:

        【解决方案4】:

        在每个属性声明之前放置以下属性:

          //[DisplayName("Your desired human readable field caption ")]
            [DisplayName("ID")]
            public int id { 
                get {return _id;}
                set { SetField(ref _id, value, "id"); } 
            }
        

        【讨论】:

          猜你喜欢
          • 2011-07-11
          • 1970-01-01
          • 2010-09-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-07
          • 2021-07-23
          • 1970-01-01
          相关资源
          最近更新 更多