2014-10-01 38 views
0

有了这个简单的类获取属性:从属性值

public class Book 
{ 
    [DataMember] 
    [Column("Bok_Name")] 
    [Author("AuthorName")] 
    public string Name{ get; set; } 

    [DataMember] 
    [Column("Bok_Publisher")] 
    public string Publisher{ get; set; } 
} 

如何,我可以从一个属性知道该属性的类型是列和值Bok_Name获得的PropertyInfo。我试图用linq查询来做到这一点。

+0

我没有得到您的问题?你想要得到什么?你可以发布你想要达到的任何例子吗? – Ehsan 2014-10-01 23:20:41

+0

我首先想到,访问所有属性及其属性,然后将其与您想要的属性 – 2014-10-01 23:21:46

+0

@Ehsan进行比较。类似于PropertyInfo pInfo = t.GetProperties()。其中​​(a => a.GetCustomAttribute(ColumnAttribute).Value ==“Bok_Name”);. – CodingWolf 2014-10-01 23:22:46

回答

1

使用反射和.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 
} 
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"); 
+2

还应该注意'GetCustomAttribute'是一个扩展方法,因此您需要添加'使用System.Reflection;'这个工作。 – 2014-10-01 23:28:13