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

Posted

技术标签:

【中文标题】是否有用于指定属性“显示名称”的 .NET 属性?【英文标题】:Is there a .NET attribute for specifying the "display name" of a property? 【发布时间】: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 中了吗?

【问题讨论】:

【参考方案1】:

是的,有System.ComponentModel.DisplayNameAttribute

【讨论】:

从 .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。它还具有OrderGroupNameShortName 等细节,以及在自动生成完成时是否显示属性(使用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");  
    

【讨论】:

以上是关于是否有用于指定属性“显示名称”的 .NET 属性?的主要内容,如果未能解决你的问题,请参考以下文章

asp.net razor page 其他

在 JComboBox 中显示属性并注册另一个属性

asp.net页面指令page啥属性能指定编辑语言

在.Net中如何判断一个属性是值类型还是引用类型

vb.net 仅外部属性或方法

.NET DefaultValue 属性