C# 中的私有内部类 - 为什么它们不经常使用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/454218/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:59:50  来源:igfitidea点击:

Private inner classes in C# - why aren't they used more often?

c#scopeinner-classes

提问by Sylvain Rodrigue

I am relatively new to C# and each time I begin to work on a C# project (I only worked on nearly mature projects in C#) I wonder why there are no inner classes?

我对 C# 比较陌生,每次我开始处理 C# 项目时(我只在 C# 中处理过近乎成熟的项目),我想知道为什么没有内部类?

Maybe I don't understand their goal. To me, inner classes -- at least private inner classes -- look a lot like "inner procedures" in Pascal / Modula-2 / Ada : they allow to break down a main class in smaller parts in order to ease the understanding.

也许我不明白他们的目标。对我来说,内部类——至少是私有内部类——看起来很像 Pascal/Modula-2/Ada 中的“内部过程”:它们允许将主类分解成更小的部分,以便于理解。

Example : here is what is see most of the time :

示例:这是大多数时间看到的内容:

public class ClassA
{
   public MethodA()
   {
      <some code>
      myObjectClassB.DoSomething(); // ClassB is only used by ClassA
      <some code>
   }
}

public class ClassB
{
   public DoSomething()
   {
   }
}

Since ClassB will be used (at least for a while) only by ClassA, my guess is that this code would be better expressed as follow :

由于 ClassB 将仅由 ClassA 使用(至少有一段时间),我猜测这段代码会更好地表达如下:

   public class ClassA
   {
      public MethodA()
      {
         <some code>
         myObjectClassB.DoSomething(); // Class B is only usable by ClassA
         <some code>
      }

      private class ClassB
      {
         public DoSomething()
         {
         }
      }
   }

I would be glad to hear from you on this subject - Am I right?

我很高兴收到你关于这个主题的消息——我说得对吗?

采纳答案by Jon Skeet

Nested classes (probably best to avoid the word "inner" as nested classes in C# are somewhat different to inner classes in Java) can indeed be very useful.

嵌套类(可能最好避免使用“内部”这个词,因为 C# 中的嵌套类与 Java 中的内部类有些不同)确实非常有用。

One pattern which hasn't been mentioned is the "better enum" pattern - which can be even more flexible than the one in Java:

一种未被提及的模式是“更好的枚举”模式——它比 Java 中的模式更灵活:

public abstract class MyCleverEnum
{
    public static readonly MyCleverEnum First = new FirstCleverEnum();
    public static readonly MyCleverEnum Second = new SecondCleverEnum();

    // Can only be called by this type *and nested types*
    private MyCleverEnum()
    {
    }

    public abstract void SomeMethod();
    public abstract void AnotherMethod();

    private class FirstCleverEnum : MyCleverEnum
    {
        public override void SomeMethod()
        {
             // First-specific behaviour here
        }

        public override void AnotherMethod()
        {
             // First-specific behaviour here
        }
    }

    private class SecondCleverEnum : MyCleverEnum
    {
        public override void SomeMethod()
        {
             // Second-specific behaviour here
        }

        public override void AnotherMethod()
        {
             // Second-specific behaviour here
        }
    }
}

We could do with some language support to do some of this automatically - and there are lots of options I haven't shown here, like not actually using a nested class for all of the values, or using the same nested class for multiple values, but giving them different constructor parameters. But basically, the fact that the nested class can call the private constructor gives a lot of power.

我们可以使用一些语言支持来自动完成其中的一些操作——这里有很多选项我没有展示,比如实际上不对所有值使用嵌套类,或者对多个值使用相同的嵌套类,但给他们不同的构造函数参数。但基本上,嵌套类可以调用私有构造函数的事实提供了很多功能。

回答by Tom Anderson

For me personally I only create private inner classes if I need to create in-process collections of an object that may require methods on them.

就我个人而言,如果我需要创建可能需要方法的对象的进程内集合,我只会创建私有内部类。

Otherwise, it could cause confusion for other developers working on the project to actually find these classes, as they are not very clear as to where they are.

否则,可能会导致从事该项目的其他开发人员无法实际找到这些类,因为他们不太清楚它们的位置。

回答by Wim Coenen

You should limit the responsibilities of each class so that each one stays simple, testable and reusable. Private inner classes go against that. They contribute to the complexity of the outer class, they are not testable and they are not reusable.

您应该限制每个类的职责,以便每个类都保持简单、可测试和可重用。私有内部类与此相反。它们增加了外部类的复杂性,它们不可测试且不可重用。

回答by matt_dev

The Framework Design Guidelineshas the best rules for using nested classes that I have found to date.

框架设计指南对使用嵌套类,我发现迄今最好的规则。

Here's a brief summary list:

这是一个简短的摘要列表:

  1. Do use nested types when the relationship between type and nested type is such the member-accessibility semantics are desired.

  2. Do NOTuse public nested types as a logical group construct

  3. Avoid using publicly exposed nested types.

  4. Do NOTuse nested types if the type is likely to be referenced outside of the containing type.

  5. Do NOTuse nested types if they need to be instantiated by client code.

  6. Do NOTdefine a nested type as a member of an interface.

  1. 当类型和嵌套类型之间的关系是需要成员可访问性语义时,请使用嵌套类型。

  2. 千万不要使用公共嵌套类型的逻辑组结构

  3. 避免使用公开暴露的嵌套类型。

  4. 千万不要,如果类型很可能被引用包含类型之外使用嵌套类型。

  5. 千万不要,如果他们需要通过客户机代码实例化使用嵌套类型。

  6. NOT限定嵌套类型作为接口的成员。