[英]Get property from attribute value
具有这个简单的类:
public class Book
{
[DataMember]
[Column("Bok_Name")]
[Author("AuthorName")]
public string Name{ get; set; }
[DataMember]
[Column("Bok_Publisher")]
public string Publisher{ get; set; }
}
我如何知道属性类型为Column且值为Bok_Name,如何从属性中获取PropertyInfo。 我试图用linq查询来做到这一点。
使用反射和.NET扩展名CustomAttributeExtensions.GetCustomAttribute {T}方法,可以找到具有自定义属性的属性。 在这种情况下,自定义属性来自System.ComponentModel.DataAnnotations.Schema.ColumnAttribute
。
var book = new Book { Name = "Jitterbug Perfume" };
PropertyInfo bokName = typeof(Book)
.GetProperties(BindingFlags.Public | BindingFlags.Instance) // add other bindings if needed
.FirstOrDefault(x => x.GetCustomAttribute<ColumnAttribute>() != null
&& x.GetCustomAttribute<ColumnAttribute>().Name.Equals("Bok_Name", StringComparison.OrdinalIgnoreCase));
// the above query only gets the first property with Column attribute equal to "Bok_Name"
// if there are more than one, then use a .Where clause instead of FirstOrDefault.
if (bokName != null)
{
string name = bokName.GetValue(book).ToString();
// do other stuff
}
var type = typeof (Book); //or var type=instance.GetType();
var res=type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(
p =>
(p.GetCustomAttribute<ColumnAttribute>() ?? new ColumnAttribute()).Value == "Bok_Name");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.