Retrieving Classes within a Namespace in C#
In C#, obtaining all classes within a specific namespace requires an indirect approach. To accomplish this:
Enumerate Assembly Types:
Filter by Namespace:
The following code snippet demonstrates this process:
private Type[] GetTypesInNamespace(Assembly assembly, string nameSpace) { return assembly.GetTypes() .Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)) .ToArray(); }
Example usage:
Assembly executingAssembly = Assembly.GetExecutingAssembly(); Type[] typelist = GetTypesInNamespace(executingAssembly, "MyNamespace"); for (int i = 0; i < typelist.Length; i++) { Console.WriteLine(typelist[i].Name); }
For .NET versions prior to 2.0, where Assembly.GetExecutingAssembly() is unavailable:
Assembly myAssembly = typeof(<Namespace>.<someClass>).GetTypeInfo().Assembly; Type[] typelist = GetTypesInNamespace(myAssembly, "<Namespace>"); for (int i = 0; i < typelist.Length; i++) { Console.WriteLine(typelist[i].Name); }
The above is the detailed content of How to Retrieve All Classes within a Specific Namespace in C#?. For more information, please follow other related articles on the PHP Chinese website!