在C#中使用内部类 [英] Using Inner classes in C#

查看:576
本文介绍了在C#中使用内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是关于C#的使用和内部类结构的最佳实践。

What are the best practices regarding the use and structure of inner classes in C#.

举例来说,如果我有一个非常大的基类和两个大型内部类,我应该将它们分割成单独的(局部类)codefiles或将它们作为一个非常大的笨重$ C $的CFile?

For instance if I have a very large base class and two large inner classes should I split them up into separate (partial class) codefiles or leave them as one very large unwieldy codefile?

也是它不好的做法,有一个抽象类,与公共继承内部类?

Also is it bad practice to have an abstract class, with a public inherited inner class?

推荐答案

通常情况下,我保留内班的两个目的之一:

Typically I reserve inner-classes for one of two purposes:


  1. 公共类从它们的父类派生那里的父类是具有一个或多个抽象方法的抽象基本实现每个子类是服务于特定的实现的实现。的阅读框架设计和指导我看到这个被标记为避免,但我用它在类似枚举的情景后 - althogh这可能给人一种不好的IM pression以及

的内部类是专用的,有商业逻辑的单位或以其他的方式紧密耦合到它们的父类,其中消耗掉或通过任何其他类使用时,它们基本上是破

The inner classes are private and are units of business logic or otherwise tightly coupled to their parent class in a manner in which they are fundamentally broken when consumed or used by any other class.

对于所有其他情况下,我尽量让他们在相同的命名空间和相同的访问级别为他们的消费/逻辑父 - 与那些比主类有点不太友好的名字经常

For all other cases I try to keep them in the same namespace and the same accessibility level as their consumer/logical parent--often with names that are a little less friendly than the "main" class.

在大的项目,你会惊奇地发现,你怎么可能经常会发现自己开始建立一个强耦合组件只是因为它是第一或主要目的,使得它看起来合乎逻辑的 - 但除非你有一个非常好的或技术原因将其锁定下来,从视线中隐藏起来再有就是在揭露类,以便其他部件可以使用它危害不大。

On big projects you'd be surprised how often you may find yourself initially building a strongly-coupled component just because it's first or primary purpose makes it seem logical--however unless you have a very good or technical reason to lock it down and hide it from sight then there is little harm in exposing the class so that other components can consume it.

修改请记住,即使我们谈论的子类,他们应该更多或更少精心设计和松散耦合的组件。即使他们是专用的,不可见的外部世界保持类之间的最小的表面积将大大缓解您的code为将来的扩展或变更的可维护性。

Edit Keep in mind that even though we're talking about sub-classes they should be more-or-less well designed and loosely coupled components. Even if they are private and invisible to the outside world keeping a minimal "surface area" between classes will greatly ease the maintainability of your code for future expansion or alteration.

这篇关于在C#中使用内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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