测试Type是属性吗?

时间:2012-02-07 08:25:15

标签: c# attributes

我得到了以下代码:

var library = Assembly.LoadFrom(libraryPath);

var namespaces = library.GetTypes().GroupBy(t => t.Namespace);
foreach (var typesInNamespace in namespaces)
{
    foreach (var type in typesInNamespace)
    {
        [...]
    }
}

但是当我想测试当前Type是否是具有以下代码的属性时:

var attributes = typesInNamespace.Where(t => t is System.Attribute);

if (type is System.Attribute)

他们都失败了,我有以下警告:

The given expression is never of the provided ('System.Attribute') type

这些类的定义如下:

class ImportableModelAttribute : Attribute
{
}

class ImportableAttribute : Attribute
{
}

说实话,我期待一种API来处理属性(类似于if (type.IsAtteribute)),但我找不到任何东西,这就是我试图这样做的原因!

1 个答案:

答案 0 :(得分:5)

Type本身永远不是属性(与typeof(string)不是字符串的方式相同),但我怀疑你想要:

if (typeof(Attribute).IsAssignableFrom(type))

(当然,或者把它放在lambda experssion中。)

有关详细信息,请参阅Type.IsAssignableFrom的文档。