在C#中另一个类中声明的类

在C#中另一个类中声明的类

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

问题描述

我正在处理一些旧代码,并遇到了一些我不确定的东西。我们有一个类y 在另一个类x 中声明。 类y 只能在 class x 中使用,但我的问题是为什么不创建一个单独的类文件并把 class y 放在里面,而不是在 class x 中声明它?这不是违反OOP的或者它只是一个风格的问题,因为它只有在这个类中使用。我重构了一些代码,我的第一反应是将 class y 分成它自己的文件。

I am working on some legacy code and have come across something that I'm not sure of. We have a class y that is declared inside of another class x. Class y is only ever used inside of class x but my question is why wouldn't you create a separate class file and put class y in there instead of declaring it inside of class x? Isn't this violating OOP's or is it just a matter of style since it is only ever used inside of this class. I'm refactoring some of this code and my first reaction would be to separate class y out into it's own file.

namespace Library
{
   public class x
   {
      // methods, properties, local members of class x

      class y
      {
         // methods, properties, local members of class y
      }
   }
}


推荐答案

您创建一个内部类,因为它只能在类x并且它在逻辑上适合于类x的因式分解/体系结构。

You create an inner class because it is only ever used within the scope of class x and it logically fits in the factoring/architecture of class x.

类y也可能不熟悉类x的实现细节,而不是公开的。

Class y might also be privy to implementation details of class x that are not meant to be known to the public.

这篇关于在C#中另一个类中声明的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 21:22