简体   繁体   English

在特定目录中获取所有名称空间

[英]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. 其中Project是名称空间,ClassA是类名称。 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: 如果要过滤该列表,只需添加一个Where子句:

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}");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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