C# 在命名空间结构中公开继承层次结构是一个坏主意吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it a bad idea to expose inheritance hierarchy in namespace structure?
提问by Luke
I've got a group of inter-related classes that are all overridden together to create a particular implementation. I'm wondering if it is a good idea to enclose the interrelated subclasses in a namespace.
我有一组相互关联的类,它们一起被覆盖以创建特定的实现。我想知道将相互关联的子类包含在命名空间中是否是个好主意。
For example purposes, consider the following namespaces and classes:
例如,请考虑以下命名空间和类:
namespace Protocol
{
public abstract class Message { }
public abstract class Driver { }
}
namespace Protocol.Tcp
{
public class TcpMessage : Message { }
public class TcpDriver : Driver { }
}
namespace Protocol.Ftp
{
public class FtpMessage : Message { }
public class FtpDriver : Driver { }
}
What is the best way to structure the namespaces? It seems unavoidable to expose the inheritance in the namespace since the base classes don't really belong in either the Protocol.Tcp namespace or the Protocol.Ftp namespace.
构造命名空间的最佳方法是什么?在命名空间中公开继承似乎是不可避免的,因为基类实际上并不属于 Protocol.Tcp 命名空间或 Protocol.Ftp 命名空间。
采纳答案by Rob Cooper
I think you are perhaps worrying too much!
我想你可能是担心太多了!
Does it make sense logically? Do you know where to find your code within the namespaces?
这在逻辑上有意义吗?您知道在命名空间中的何处可以找到您的代码吗?
I would much rather see a codebase like the above with a small number of classes, relevant to the name with a hierarchy, than one large namespace where everything is interrelated..
我更愿意看到像上面这样的代码库,其中包含少量与具有层次结构的名称相关的类,而不是一个所有内容都相互关联的大型命名空间。
Remember, namespacing is there for precisely this, to organise your codebase logically
请记住,命名空间正是为此,以逻辑方式组织您的代码库
What you have seems logical :)
你所拥有的似乎合乎逻辑:)
EDIT:
编辑:
As an example:
举个例子:
using System.Data;
using System.Data.Sql;
;)
;)
回答by mmattax
If this were me, I would define 2 namespaces:
如果这是我,我会定义 2 个命名空间:
Protocol
and
和
Protocol.Driver
Dividing the namespace like this separates your "library code" vs your "executable / test code." I also create my namespaces to match the directory structure; it will give logic to your programs structure and codefiles. (maybe you already do this...)
像这样划分命名空间将“库代码”与“可执行/测试代码”分开。我还创建了命名空间以匹配目录结构;它将为您的程序结构和代码文件提供逻辑。(也许你已经这样做了......)
回答by Ronnie
The original tags show that this post is about C# - therefore multiple inheritance is an irrelevancy - you can't multiply inherit in C#.
原始标签显示这篇文章是关于 C# 的——因此多重继承是无关紧要的——你不能在 C# 中多重继承。
Maybe you should consider defining some interfaces that define what the basic contracts of a Message
and a Driver
are and then you may feel a little free-er to use the namespace structure to mimic the technology differences.
也许你应该考虑定义一些接口来定义 aMessage
和 a的基本契约是什么Driver
,然后你可能会觉得使用命名空间结构来模仿技术差异更自由一些。