I have something that looks like the following:
我有一些看起来如下的东西:
[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
}
}
and then I would call it like so:
然后我会这样称呼它:
TestSomeInterfaceStuff<IThing>();
However, when I do this, it doesn't return any attributes at all.
但是,当我这样做时,它根本不会返回任何属性。
Thoughts?
1 个解决方案
#1
The "in" line needs adjusting. It should read
“在”线需要调整。它应该读
in typeof(T).GetCustomAttributes(typeof(CoolnessFactorAttribute), true)
The type passed into the GetCustomAttributes method identifies the type of attributes that you are looking for. It also means the following where clause is unnecessary and can be removed.
传递给GetCustomAttributes方法的类型标识了您要查找的属性类型。它还意味着以下where子句是不必要的,可以删除。
Once you remove that clause though, it removes the need for the query. The only real improvement that can be done is to cast the result in order to get a strongly typed collection.
删除该子句后,它将不再需要查询。可以做的唯一真正的改进是转换结果以获得强类型集合。
var attributes =
typeof(T).GetCustomAttributes(typeof(CoolnessFactorAttribute),true)
.Cast<CoolnessFactorAttribute>();
#1
The "in" line needs adjusting. It should read
“在”线需要调整。它应该读
in typeof(T).GetCustomAttributes(typeof(CoolnessFactorAttribute), true)
The type passed into the GetCustomAttributes method identifies the type of attributes that you are looking for. It also means the following where clause is unnecessary and can be removed.
传递给GetCustomAttributes方法的类型标识了您要查找的属性类型。它还意味着以下where子句是不必要的,可以删除。
Once you remove that clause though, it removes the need for the query. The only real improvement that can be done is to cast the result in order to get a strongly typed collection.
删除该子句后,它将不再需要查询。可以做的唯一真正的改进是转换结果以获得强类型集合。
var attributes =
typeof(T).GetCustomAttributes(typeof(CoolnessFactorAttribute),true)
.Cast<CoolnessFactorAttribute>();