命名空间和类同名? [英] Namespace and class with the same name?

查看:65
本文介绍了命名空间和类同名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在组织一个库项目,我有一个名为 Scenegraph 的中央管理器类和位于 Scenegraph 命名空间中的一大堆其他类.

I'm organizing a library project and I have a central manager class named Scenegraph and a whole bunch of other classes that live in the Scenegraph namespace.

我真正想要的是场景图是 MyLib.Scenegraph 而其他类是 MyLib.Scenegraph.*,但这似乎是唯一的方法这样做会使所有其他类成为 Scenegraph.cs 文件中 Scenegraph 的内部类,这太笨拙了.

What I'd really like is for the scenegraph to be MyLib.Scenegraph and the other classes to be MyLib.Scenegraph.*, but it seems the only way to do that would be to make all the other classes inner classes of Scenegraph in the Scenegraph.cs file and that's just too unwieldy.

相反,我将其组织为 Mylib.Scenegraph.ScenegraphMyLib.Scenegraph.*,哪种有效,但我发现 Visual Studio 在某些情况下变得混乱关于我指的是类还是命名空间的条件.

Instead, I've organized it as Mylib.Scenegraph.Scenegraph and MyLib.Scenegraph.*, which sort of works but I find Visual Studio gets confused under some conditions as to whether I am referring to the class or the namespace.

有没有一种好方法来组织这个包,这样用户就不会将我的所有代码放在一起,使之成为不可维护的混乱?

Is there a good way to organize this package so it's convenient for users without glomming all my code together in an unmaintainable mess?

推荐答案

我不建议您像命名空间那样命名类,请参阅 这篇文章.

I don't recommend you to name a class like its namespace, see this article.

框架设计指南在 3.4 节中说不要使用命名空间和该命名空间中的类型的名称相同".即:

The Framework Design Guidelines say in section 3.4 "do not use the same name for a namespace and a type in that namespace". That is:

namespace MyContainers.List 
{ 
    public class List { … } 
}

为什么这是坏事?哦,让我数数.

Why is this badness? Oh, let me count the ways.

你可以让自己陷入你认为你所指的情况指一件事,但实际上是指另一件事.假设你最终陷入这种不幸的境地:您正在编写 Blah.DLL 和导入 Foo.DLL 和 Bar.DLL,不幸的是,它们都有一个类型叫 Foo:

You can get yourself into situations where you think you are referring to one thing but in fact are referring to something else. Suppose you end up in this unfortunate situation: you are writing Blah.DLL and importing Foo.DLL and Bar.DLL, which, unfortunately, both have a type called Foo:

// Foo.DLL: 
namespace Foo { public class Foo { } }

// Bar.DLL: 
namespace Bar { public class Foo { } }

// Blah.DLL: 
namespace Blah  
{   
using Foo;   
using Bar;   
class C { Foo foo; } 
}

编译器报错.Foo"在 Foo.Foo 和Bar.Foo. 无赖.我想我会通过完全限定名称来解决这个问题:

The compiler gives an error. "Foo" is ambiguous between Foo.Foo and Bar.Foo. Bummer. I guess I’ll fix that by fully qualifying the name:

   class C { Foo.Foo foo; } 

这现在给出了歧义错误Foo inFoo.Foo 在 Foo.Foo 和 Bar.Foo 之间有歧义".我们还不知道第一个 Foo 指的是什么,在我们弄清楚之前,我们甚至不用费心去弄清楚第二个指的是什么.

This now gives the ambiguity error "Foo in Foo.Foo is ambiguous between Foo.Foo and Bar.Foo". We still don’t know what the first Foo refers to, and until we can figure that out, we don’t even bother to try to figure out what the second one refers to.

这篇关于命名空间和类同名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆