简体   繁体   中英

Relationship between Assembly and Namespace in .NET framework?

I know that it's possible to have many classes in a namespace. Now, is it possible to have a class in more than one assembly (.dll file)?

No you can't span a class over multiple assemblies.
If you create Namespace1.Class1 in assembly1 & Namespace1.Class1 in assembly2 , then you reference both assemblies in your project, you'll have:

  • 2 different classes
  • compile error (conflict): The type 'Namespace1.Class1' exists in both 'assembly1.dll' and 'assembly2.dll' ...

I think it is not posible. At most, you can spawn a class definition across multiple files in the same assembly (partial classes).

If you define two classes in two separate namespaces, you have two distinct classes, existing in two distinct namespaces that have nothing whatsoever to do with each other. To the CLR, they look like this:

NamespaceA.ClassA
NamespaceB.ClassA

Even if you mark them partial, they are still distinct classes in separate namespaces. This is because namespaces are simply prepended to the name of the class when the class is compiled. Aside from that, the CLR is unaware of the notion of namespaces or partial classes. It's all compiler magic.

Clarification : When defining a partial type, you're defining a type . A type is never split across an assembly or a namespace.

Why would you want to do this even if you could? What technical or business problem would be solved by doing this? .NET has partial classes that allow you to spread a class over multiple files if so desired. You can also extend behavior of classes using extension methods where you can define your methods in a separate assembly from the class you wish to extend.

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