2009-07-16 75 views
0

我有一个函数接收一个类型并返回true或false。 我需要找出哪些是所有类型的特定名称空间,该函数将为他们返回true。 谢谢。有没有办法在foreach循环中的所有类型的命名空间?

+0

不严格相关foreach循环,但类似的问题:HTTP://计算器.com/questions/79693/getting-all-types-in-a-namespace-via-reflection – Utaal 2009-07-16 10:01:58

回答

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

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

0123。

应该做的工作=)

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; 
    } 
} 
相关问题