如何访问从code中的显示名称数据注解的价值? [英] How can I access the DisplayName data annotation value from code?
本文介绍了如何访问从code中的显示名称数据注解的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
公共静态字符串ProductHelper(此产品p){
//需要获得p.Name属性DisplayName值
}
编辑:
[MetadataType(typeof运算(ProductMetadata))]
公共部分类产品{
公共类ProductMetadata {
[显示名称(产品名称)]
公共对象名称{;组; }
}
}
解决方案
类型类型= typeof运算(产品);
DisplayNameAttribute ATT =(DisplayNameAttribute)type.GetProperty(姓名)GetCustomAttributes(typeof运算(DisplayNameAttribute),真).SingleOrDefault()。
这假定属性始终存在。修改的情况下也可能不是。
编辑:结果
为了获取值字符串x = att.DisplayName;
如果产品是一个基类使用类型类型= p.GetType();
而不是
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; }
}
}
解决方案
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.
这篇关于如何访问从code中的显示名称数据注解的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文