Is there a .NET attribute for specifying the “display name” of a property?

徘徊边缘 提交于 2020-01-22 17:56:07

问题


Is there a property that allows you to specify a user friendly name for a property in a class?

For example, say I have the following class:

public class Position
{
     public string EmployeeName { get; set; }
     public ContactInfo EmployeeContactInfo { get; set; }
}

I'd like to specify that the display name for the EmployeeName property is "Employee Name" and the display name for the EmployeeContactInfo property is "Employee Contact Information".

It's easy enough to write my own attribute class that allows me to do this:

[PropertyDisplayInfo(DisplayName = "Employee Name")]
public string EmployeeName { get; set; }

But is something like this already included in .NET?


回答1:


Yes, there is System.ComponentModel.DisplayNameAttribute




回答2:


System.ComponentModel.DataAnnotations.DisplayAttribute is a better choice than DisplayNameAttribute, which is actually intended for use in property grids. Nowadays more components in the .NET world will pick up on and use DisplayAttribute. It also has niceties like Order, GroupName, ShortName and whether to display the property at all, when auto generation is done (with AutoGenerateField).

DisplayAttribute is also resource friendly, making it a good choice for localization.




回答3:


If you want this for debugging, you might be interested in the DebuggerDisplayAttribute.




回答4:


Place the following attribute before each property declaration:

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


来源:https://stackoverflow.com/questions/3580347/is-there-a-net-attribute-for-specifying-the-display-name-of-a-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!