简体   繁体   English

.NET用于单个类的多个命名空间

[英].NET Multiple Namespaces for single class

Is it possible to have a single class reside within two name-spaces and how can I do this? 是否可以让一个类驻留在两个名称空间内,我该怎么做?

To clarify: We have a class library (let say root namespace is classLib1), which has grown over time (more classes) and I want to logically group classes into different namespaces. 澄清一下:我们有一个类库(比如root命名空间是classLib1),它随着时间的推移而增长(更多的类),我想在逻辑上将类分组到不同的命名空间。 However some of the older classes need to be grouped into these new namespaces (eg classLib1.section1) and doing so will break legacy code in other assemblys that use this class library. 但是,某些较旧的类需要分组到这些新的命名空间(例如classLib1.section1),这样做会破坏使用此类库的其他程序集中的遗留代码。 So I want to be able to refer to a class using both name-spaces until we can phase the old ones out. 所以我希望能够使用两个名称空间引用一个类,直到我们可以逐步淘汰旧的类。

I can't find any information on this, which suggests there is a reason that people would not want to do this!?! 我找不到任何关于此的信息,这表明人们不想这样做的原因!?!

No, there is no way to give a single class two names (the namespace is actually just a part of the class name). 不,没有办法给单个类两个名称(名称空间实际上只是类名的一部分)。

As a workaround, you could move the classes to their new location, and create thin wrappers around them at the old location (Facade Pattern). 作为一种变通方法,您可以将类移动到新位置,并在旧位置(Facade Pattern)周围创建薄包装器。 A better solution, of course, would be to move the classes and fix the legacy code accordingly. 当然,更好的解决方案是移动类并相应地修复遗留代码。

As a work around you can 'using' the class into the second namespace when you need it: 作为一种解决方法,您可以在需要时将该类“使用”到第二个命名空间中:

namespace classLib1.section2
{
    public myBigClass
    {

and in every file which uses it in the old namespace you can add one line 并且在旧命名空间中使用它的每个文件中,您都可以添加一行

namespace classLib1.section1
{
    using myBigClass = classLib1.section2.myBigClass;

as a temporary patch-up until you've fixed this properly. 作为临时补丁,直到你正确修复它。

Type Forwarding was introduced in .net 2.0, which means you can use the TypeForwardedToAttribute attribute to indicate that a type which was originally present in AssemblyX is now to be found in AssemblyY. 类型转发是在.net 2.0中引入的,这意味着您可以使用TypeForwardedToAttribute属性来指示现在可以在AssemblyY中找到最初存在于AssemblyX中的类型。

I'm fairly sure this is only appropriate/applicable if you're separating out into multiple assemblies, but is worth knowing even if not. 我很确定如果你分成多个组件,这只是适当的/适用的,但即使没有,也值得知道。

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

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