2009-07-10 26 views
0

回到我的東西,看起來像下面這樣:CustomAttributes不被按預期

[CoolnessFactor] 
interface IThing {} 

class Tester 
{ 
    static void TestSomeInterfaceStuff<T>() 
    { 
     var attributes = from attribute 
         in typeof(T).GetCustomAttributes(typeof(T), true) 
         where attributes == typeof(CoolnessFactorAttribute) 
         select attribute; 
     //do some stuff here 
    } 
} 

,然後我會叫它像這樣:

TestSomeInterfaceStuff<IThing>(); 

然而,當我這樣做,它根本不返回任何屬性。

想法?

回答

5

「in」行需要調整。它應該是

in typeof(T).GetCustomAttributes(typeof(CoolnessFactorAttribute), true) 

傳遞給GetCustomAttributes方法的類型標識了您正在查找的屬性的類型。這也意味着以下where子句是不必要的並且可以被刪除。

雖然刪除了該子句,但它不需要查詢。可以做的唯一真正的改進是投射結果以獲得強類型集合。

var attributes = 
    typeof(T).GetCustomAttributes(typeof(CoolnessFactorAttribute),true) 
    .Cast<CoolnessFactorAttribute>();