从属性值获取属性

时间:2014-10-01 23:17:26

标签: c# system.reflection

有这个简单的课程:

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查询来做这件事。

2 个答案:

答案 0 :(得分:3)

使用反射和.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
}

答案 1 :(得分:2)

    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");
相关问题