简体   繁体   English

目录中的C#类,其名称空间中没有目录名

[英]C# class in a directory without having the directory name in its namespace

If you add a directory in your Visual Studio project and you add a class inside it, the namespace will respect the whole path the directory inclusive. 如果在Visual Studio项目中添加目录并在其中添加class ,则namespace遵循包含该目录的整个路径

But sometimes, I prefer having the class in the main project namespace , although it lies in a directory structure, just because I don't want to have mess in my code. 但有时候,我更喜欢在主项目命名空间中使用该类,尽管它位于目录结构中,只是因为我不想让我的代码混乱。 So often happens that I rewrite the Myproject.MyDirectory namespace to be Myproject only. 因此,我经常将Myproject.MyDirectory命名空间重写Myproject.MyDirectory Myproject

Is it OK in your opinion? 你认为这样可以吗? Or does any convention say that every class inside the directory must have it included in the namespace ? 或者是否有任何约定表明目录中的每个类都必须将它包含在命名空间中?

Thanks 谢谢

There isn't any convention restricting from what you're trying to do. 没有任何约定限制你正在尝试做什么。 I usually have multiple directories in my project to organize class files and use different namespaces with no respect to the directory structure and I don't have any problems. 我的项目中通常有多个目录来组织类文件并使用不同的命名空间而不考虑目录结构,我没有任何问题。

There is no constraint, but some think it's useful to have the namespace identical to the path. 没有约束,但有些人认为让命名空间与路径相同是有用的。 So you could choose any namespace and place the class file wherever you want. 因此,您可以选择任何命名空间并将类文件放在任何位置。

In my view, folders and namespaces serve for different purposes. 在我看来,文件夹和命名空间用于不同的目的。

Folders are useful to provide a clear hierarchy for people who read your code 文件夹对于为阅读代码的人员提供清晰的层次结构非常有用

Namespaces are useful to provide a clear hierarchy for people who use your code. 命名空间对于为使用代码的人员提供清晰的层次结构非常有用。 Eg calling the API provided by your code, when they don't see the actual source code. 例如,当他们看不到实际的源代码时,调用代码提供的API。

Therefore, inconsistency is perfectly fine, as long as each makes sense. 因此,只要每个都有意义,不一致就完全没问题。

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

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