2012-07-30 72 views
1

我有3个属性的类。如何通过自定义属性来选择某个属性的某些属性

class Issuance 
{ 
    [MyAttr] 
    virtual public long Code1 { get; set; } 

    [MyAttr] 
    virtual public long Code2 { get; set; } 

    virtual public long Code3 { get; set; } 
} 

我需要我的自定义属性([MyAttr])选择一些在这个类的属性。

我使用GetProperties()但是这返回所有属性。

var myList = new Issuance().GetType().GetProperties(); 
//Count of result is 3 (Code1,Code2,Code3) But count of expected is 2(Code1,Code2) 

我该怎么办?

+1

您需要在每个属性上使用GetCustomAttributes并检查返回的属性是否属于MyAttr类型。 – Charleh 2012-07-30 14:27:54

回答

8

只需使用LINQ和使用MemberInfo.IsDefined一个Where条款:

var myList = typeof(Issuance).GetProperties() 
          .Where(p => p.IsDefined(typeof(MyAttr), false); 
+1

这真是太棒了Jon,我不认为我曾经使用过IsDefined - 这只是GetCustomAttributes的包装? – Charleh 2012-07-30 14:33:27

+0

@Charleh:我不知道 - 但它确实更简单:) – 2012-07-30 14:34:55

+0

好吧,任何削减代码行的东西都会让我的投票! – Charleh 2012-07-30 14:36:21

0

http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getcustomattributes.aspx

试试这个 - 基本上做的属性在foreach,看你回来为每个属性的属性类型。如果这样做,那么该属性具有以下属性:

foreach(var propInfo in new Issuance().GetType().GetProperties()) 
{ 
    var attrs = propInfo.GetCustomAttributes(typeof(MyAttr), true/false); // Check docs for last param 

    if(attrs.Count > 0) 
     // this is one, do something 
}