C#,是否可以使用嵌套类进行逻辑结构? [英] C#, is it okay to use nested classes for logical structure?

查看:118
本文介绍了C#,是否可以使用嵌套类进行逻辑结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于使用嵌套类的争论。情况是,在两个或更多个地方重复一个类名称,而在每个不同的实例之间存在中等的相似性,它们通常是不同的。这个嵌套类并不经常(如果有的话)超出了他们父类的范围。



那么,而不是只提出三个不同的类名,这个似乎对我来说更有意义。

  class A {
class B {
}

class M {
class B {
}
}

class Q {
class B {
}
}

这个明显的问题不是功能,而是一致性/重复。我想知道其他开发人员是否曾经遇到同样的问题,有些意见是什么。

解决方案

。net设计指南针对其提出建议




  • 不要将公共嵌套类型用作逻辑分组结构;为此使用命名空间。

  • 避免公开暴露的嵌套类型,唯一的例外是嵌套类型的变量需要在罕见的情况下声明,例如子类化或其他高级定制场景。



这也是基类库所做的:在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屋!

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