未按预期返回CustomAttributes

Jos*_*eph 0 c# attributes interface

我有一些看起来如下的东西:

[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
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我会这样称呼它:

TestSomeInterfaceStuff<IThing>();
Run Code Online (Sandbox Code Playgroud)

但是,当我这样做时,它根本不会返回任何属性.

思考?

Jar*_*Par 5

"在"线需要调整.它应该读

in typeof(T).GetCustomAttributes(typeof(CoolnessFactorAttribute), true)
Run Code Online (Sandbox Code Playgroud)

传递给GetCustomAttributes方法的类型标识了您要查找的属性类型.它还意味着以下where子句是不必要的,可以删除.

删除该子句后,它将不再需要查询.可以做的唯一真正的改进是转换结果以获得强类型集合.

var attributes = 
  typeof(T).GetCustomAttributes(typeof(CoolnessFactorAttribute),true)
  .Cast<CoolnessFactorAttribute>();
Run Code Online (Sandbox Code Playgroud)