如何从代码中访问DisplayName数据注释值?

ran*_*guy 3 data-annotations asp.net-mvc-2

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

编辑:

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

jws*_*ple 5

Type type = typeof(Product);
DisplayNameAttribute att = (DisplayNameAttribute)type.GetProperty("Name").GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault();
Run Code Online (Sandbox Code Playgroud)

这假设该属性始终存在.在不可能的情况下修改案例.

编辑:
获取值string x = att.DisplayName;

如果Product是基类使用Type type = p.GetType();.