如何获取程序集的名称空间而不是其依赖项?

How do I get the namespaces of an assembly and not its dependencies?

如何获取程序集的命名空间而不是其依赖项的命名空间?

例如,如果我使用

获取名称空间
assembly.GetTypes().Select(t => t.Namespace).Where(n => n != null).Distinct() 

难道我也得不到那个程序集的依赖项的命名空间吗?

如何区分两者?

我正在通过 Assembly.LoadFrom(path) 加载程序集,我知道它会自动加载程序集的依赖项。对于解决方案,我是否必须以不加载依赖项的方式加载程序集?如果是,我该怎么做?

此外,我无法控制程序集的创建,例如添加空 class 等

编辑:更正示例

System.Linq.Expressions其实是在EntityFramework.dll

具体来说,以下 classes 在该 DLL 中,在该命名空间下:

  • System.Linq.Expressions.EntityExpressionVisitor
  • System.Linq.Expressions.Internal.Error
  • System.Linq.Expressions.Internal.ReadOnlyCollectionExtensions

此外,您还应该看到 System.ComponentModel.DataAnnotations,因为 EntityFramework.dll 定义了 class System.ComponentModel.DataAnnotations.Schema.IndexAttribute.

** 注意,我正在检查 EntityFramework 6.0.0.0

为了更直接地回答您的问题:

How do I get the namespaces of an assembly and not of its dependencies?

assembly.GetTypes().Select(t => t.Namespace)

Would I not get the namespaces of the dependencies of that assembly as well?

没有

How do I distinguish between the 2?

N/A

For the solution, do I have to load the assembly in a way that the dependencies are not loaded?

没有

If yes, how do I do that?

N/A

Assembly.LoadFrom() 不会加载程序集的依赖项,因此您的代码将按原样执行您想要的操作。

现在,让我们假装它确实加载了依赖项;再次:它不是

假设您以某种方式获得了所有已加载程序集中的所有类型(高度人为的情况),您可以 select 仅目标程序集中的类型,然后应用您的 "distinct code."

types
    .Where(x => x.GetName().Name == "Your.Assembly.Name")
    .Select(t => t.Namespace)
    .Where(n => n != null)
    .Distinct()

加载程序集会将 "load" 所有相关程序集都存入内存,但是 Assembly object 您正在处理的仅与您要处理的程序集有关'显式加载,因此调用 GetTypes 仅加载在该程序集 中定义的类型

因此,如果您获得了意想不到的命名空间,那是因为 类型 在该程序集 中的命名空间中(命名空间中的类型不必全部包含在一个程序集中)