简体   繁体   中英

Getting all namespaces in certain directory

I am trying to find a way to retrieve all the namespaces in our test directory. All classes in the project share a same namespace, so I need to get the class as well. The results I am looking for should look like this

Project.ClassA
Project.ClassB

Where Project is the namespace and ClassA is the class name. I tried out a function like this...

assembly = Assembly.GetAssembly(typeof(System.Int32));
var groups = assembly.GetTypes().Where(t => t.IsClass);

foreach(var group in groups)
{
   Console.WriteLine(group);
}

However this is returning a bunch of System information among other things, nothing related to what I am looking for. Am I on the right track here? Also, how can I make it look only in the test directory?

This will get you all types that are part of the current app domain (ie all the types that are loaded):

var types = AppDomain.CurrentDomain
    .GetAssemblies()
    .SelectMany(a => a.GetTypes());

If you want to filter that list, just add a Where clause:

var types = AppDomain.CurrentDomain
    .GetAssemblies()
    .SelectMany(a => a.GetTypes())
    .Where(a => !string.IsNullOrEmpty(a.Namespace) && 
                a.Namespace.StartsWith("Foo"));

And do something with them:

foreach(var type in types)
{
    Console.WriteLine($"Found type {type.Name}");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM