C#,是否可以使用嵌套类进行逻辑结构? [英] C#, is it okay to use nested classes for logical structure?
问题描述
那么,而不是只提出三个不同的类名,这个似乎对我来说更有意义。
class A {
class B {
}
class M {
class B {
}
}
class Q {
class B {
}
}
这个明显的问题不是功能,而是一致性/重复。我想知道其他开发人员是否曾经遇到同样的问题,有些意见是什么。
- 不要将公共嵌套类型用作逻辑分组结构;为此使用命名空间。
- 避免公开暴露的嵌套类型,唯一的例外是嵌套类型的变量需要在罕见的情况下声明,例如子类化或其他高级定制场景。
这也是基类库所做的:在code> System.Web .UI 命名空间,你有 DataGridItem
, DataListItem
, ListViewItem
, MenuItem
, RepeaterItem
等等。所有这些可以称为 Item
并嵌套在 DataGrid
, DataList
等。但是,这将违反上述两个原则。
I am having a bit of a debate about the use of nested classes. The situation is that a class name makes sense to be repeated in two or more places, and while there is moderate similarity between each of the different instances, they are generally different. The nested classes are not often (if at all) needed beyond the scope of their parent class.
So then, rather than just coming up with three different class names, this seems to make more sense to me.
class A {
class B {
}
class M {
class B {
}
}
class Q {
class B {
}
}
The obvious problem with that is not functionality, but rather consistency/repetition. I was wondering if other developers have ever struggled with the same thing, and what some of the opinions were.
The .net Design Guide advises against it:
- "Do not use public nested types as a logical grouping construct; use namespaces for this."
- "Avoid publicly exposed nested types. The only exception to this is when variables of the nested type need to be declared in rare scenarios such as subclassing or other advanced customization scenarios."
That's also what the base class library does: In the System.Web.UI
namespace, you have DataGridItem
, DataListItem
, ListViewItem
, MenuItem
, RepeaterItem
, etc. All of these could be called Item
and nested inside DataGrid
, DataList
, etc. However, this would violate the two principles outlined above.
这篇关于C#,是否可以使用嵌套类进行逻辑结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!