代码之家  ›  专栏  ›  技术社区  ›  randomguy

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

  •  2
  • randomguy  · 技术社区  · 16 年前
    public static string ProductHelper(this Product p) {
        // Need to get the DisplayName value for p.Name property
    }
    

    编辑:

    [MetadataType(typeof(ProductMetadata))]
    public partial class Product {
        public class ProductMetadata {
            [DisplayName("Product name")]
            public object Name { get; set; }
        }
    }
    
    1 回复  |  直到 16 年前
        1
  •  5
  •   jwsample    16 年前
    Type type = typeof(Product);
    DisplayNameAttribute att = (DisplayNameAttribute)type.GetProperty("Name").GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault();
    

    这假设属性始终存在。在不适用的情况下进行修改。


    获取价值 string x = att.DisplayName;

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