有没有办法在foreach循环中遍历命名空间中的所有类型?

时间:2009-07-16 09:55:04

标签: c# reflection

我有一个接收类型并返回true或false的函数。 我需要找出某个命名空间中的所有类型,该函数将为它们返回true。 感谢。

3 个答案:

答案 0 :(得分:10)

这是一个获取命名空间中所有类的函数:

using System.Reflection;
using System.Collections.Generic;

/// <summary>
/// Method to populate a list with all the class
/// in the namespace provided by the user
/// </summary>
/// <param name="nameSpace">The namespace the user wants searched</param>
/// <returns></returns>
static List<string> GetAllClasses(string nameSpace)
{
    //create an Assembly and use its GetExecutingAssembly Method
    //http://msdn2.microsoft.com/en-us/library/system.reflection.assembly.getexecutingassembly.aspx
    Assembly asm = Assembly.GetExecutingAssembly();
    //create a list for the namespaces
    List<string> namespaceList = new List<string>();
    //create a list that will hold all the classes
    //the suplied namespace is executing
    List<string> returnList = new List<string>();
    //loop through all the "Types" in the Assembly using
    //the GetType method:
    //http://msdn2.microsoft.com/en-us/library/system.reflection.assembly.gettypes.aspx
    foreach (Type type in asm.GetTypes())
    {
        if (type.Namespace == nameSpace)
            namespaceList.Add(type.Name);
    }

    foreach (String className in namespaceList)
        returnList.Add(className);

    return returnList;
}

<强> [更新]

这是一种更紧凑的方法,但这需要.Net 3.5(来自here):

public static IEnumerable<Type> GetTypesFromNamespace(Assembly assembly, 
                                               String desiredNamepace)
{
    return assembly.GetTypes()
                   .Where(type => type.Namespace == desiredNamespace);
}

答案 1 :(得分:1)

System.Reflection.Assembly.GetTypes():获取此程序集中定义的所有类型。*

应该做的工作=)

答案 2 :(得分:1)

添加要搜索的所有程序集并实现MyFunction方法:

class Program
{
    static void Main(string[] args)
    {
        List<Assembly> assembliesToSearch = new List<Assembly>();
        // Add the assemblies that you want to search here:
        assembliesToSearch.Add(Assembly.Load("mscorlib")); // sample assembly, you might need Assembly.GetExecutingAssembly

        foreach (Assembly assembly in assembliesToSearch)
        {
            var typesForThatTheFunctionReturnedTrue = assembly.GetTypes().Where(type => MyFunction(type) == true);

            foreach (Type type in typesForThatTheFunctionReturnedTrue)
            {
                Console.WriteLine(type.Name);
            }
        }
    }

    static bool MyFunction(Type t)
    {
        // Put your logic here
        return true;
    }
}