且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在.NET为什么/时,你应该使用嵌套类?或不应该吗?

更新时间:2023-11-13 17:22:16

使用嵌套类,当你嵌套类仅用于封闭类。例如,嵌套类允许你写类似(简体):

Use a nested class when the class you are nesting is only useful to the enclosing class. For instance, nested classes allow you to write something like (simplified):

public class SortedMap {
    private static class TreeNode {
        TreeNode left;
        TreeNode right;
    }
}

您可以在一个地方你的类的完整定义,你没有经过任何PIMPL箍跳到定义如何类的工作,和外面的世界并不需要看到您的实现什么。

You can make a complete definition of your class in one place, you don't have to jump through any PIMPL hoops to define how your class works, and the outside world doesn't need to see anything of your implementation.

如果该树节点类是外在的,你要么必须让所有的字段公开或作出了一堆 get / set方法$的C $ C>的方法来使用它。外面的世界将有另一个类污染他们的智能感知。

If the TreeNode class was external, you would either have to make all the fields public or make a bunch of get/set methods to use it. The outside world would have another class polluting their intellisense.