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

时间:2010-05-27 04:00:15

标签: c# .net reflection

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

2 个答案:

答案 0 :(得分:6)

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

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

第二个参数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));
    }
}

答案 1 :(得分:0)

我终于编写了自己的ClassLoader类,它支持.NET 2.0,3.5和4.0。

static class ClassLoader
{
    public static IEnumerable<MethodInfo> GetMethodsWithAttribute(Type attributeType, Type type)
    {
        List<MethodInfo> list = new List<MethodInfo>();

        foreach (MethodInfo m in type.GetMethods())
        {
            if (m.IsDefined(attributeType, false))
            {
                list.Add(m);
            }
        }

        return list;
    }

    public static IEnumerable<Type> GetTypesWithAttribute(Type attributeType, string assemblyName)
    {
        Assembly assembly = Assembly.LoadFrom(assemblyName);
        return GetTypesWithAttribute(attributeType, assembly);
    }

    public static IEnumerable<Type> GetTypesWithAttribute(Type attributeType, Assembly assembly)
    {
        List<Type> list = new List<Type>();
        foreach (Type type in assembly.GetTypes())
        {
            if (type.IsDefined(attributeType, false))
                list.Add(type);
        }

        return list;
    }
}