如何在程序集中列出具有特定Atttribute的所有类?

Mar*_*ood 4 .net c# reflection

请帮我详细说明如何在C#中的程序集中列出具有特定属性的所有类?

Eli*_*sha 6

获取程序集中所有可序列化类型的代码示例:

public IEnumerable<Type> GetTypesWithAttribute(Assembly assembly)
{
    return assembly.GetTypes()
        .Where(type => type.IsDefined(typeof(SerializableAttribute), false));
}
Run Code Online (Sandbox Code Playgroud)

IsDefined()接收的第二个参数是是否应该在基类型上查找属性.

查找所有类型的用法示例MyDecorationAttribute:

public class MyDecorationAttribute : Attribute{}

[MyDecoration]
public class MyDecoratedClass{}

[TestFixture]
public class DecorationTests
{
    [Test]
    public void FindDecoratedClass()
    {
        var currentAssembly = Assembly.GetExecutingAssembly();
        var typesWithAttribute = GetTypesWithAttribute(currentAssembly);
        Assert.That(typesWithAttribute, 
                              Is.EquivalentTo(new[] {typeof(MyDecoratedClass)}));
    }

    public IEnumerable<Type> GetTypesWithAttribute(Assembly assembly)
    {
        return assembly.GetTypes()
            .Where(type => type.IsDefined(typeof(MyDecorationAttribute), false));
    }
}
Run Code Online (Sandbox Code Playgroud)