How can I access the DisplayName data annotation value from code?

风流意气都作罢 提交于 2019-11-26 21:57:43

问题


public static string ProductHelper(this Product p) {
    // Need to get the DisplayName value for p.Name property
}

EDIT:

[MetadataType(typeof(ProductMetadata))]
public partial class Product {
    public class ProductMetadata {
        [DisplayName("Product name")]
        public object Name { get; set; }
    }
}

回答1:


Type type = typeof(Product);
DisplayNameAttribute att = (DisplayNameAttribute)type.GetProperty("Name").GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault();

This assumes the attribute always exists. Modify for the case when it may not.

edit:
To get the value string x = att.DisplayName;

If Product is a base class use Type type = p.GetType(); instead.



来源:https://stackoverflow.com/questions/3485737/how-can-i-access-the-displayname-data-annotation-value-from-code

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