zoukankan      html  css  js  c++  java
  • Why Would I Ever Need to Use C# Nested Classes

    Why Would I Ever Need to Use C# Nested Classes [duplicate]

    A pattern that I particularly like is to combine nested classes with the factory pattern:

    public abstract class BankAccount
    {
      private BankAccount() {} // prevent third-party subclassing.
      private sealed class SavingsAccount : BankAccount { ... }
      private sealed class ChequingAccount : BankAccount { ... }
      public static BankAccount MakeSavingAccount() { ... }
      public static BankAccount MakeChequingAccount() { ... }
    }

    By nesting the classes like this, I make it impossible for third parties to create their own subclasses. I have complete control over all the code that runs in any bankaccount object. And all my subclasses can share implementation details via the base class.

    c# Public Nested Classes or Better Option? 

    The contents of a class should be the implementation details of that class. Are the nested classes implementation details of the outer class, or are you merely using the outer class as a convenient name scoping and discovery mechanism?

    If the former, then you shouldn't be making the private implementation details publically available. Make them private if they are implementation details of the class.

    If the latter, then you should be using namespaces, not outer classes, as your scoping and discovery mechanism.

    Either way, public nested classes are a bad code smell. I'd want to have a very good reason to expose a nested class.

    Why/when should you use nested classes in .net? Or shouldn't you?

    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 class TreeNode {
            TreeNode left;
            TreeNode right;
        }
    }

    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.

    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.

  • 相关阅读:
    HDOJ_1010 Tempter of the Bone
    矩阵旋转
    HDU 2544 最短路 http://acm.hdu.edu.cn/showproblem.php?pid=2544
    题目连接:http://acm.zznu.edu.cn/problem.php?id=1329
    队列/优先队列(代码简单模式)
    虚拟方法调用
    Vim中分屏(整理)
    Java Web设计模式之依赖倒换原则
    Java Web 设计模式之开闭原则
    Java 2+2=5
  • 原文地址:https://www.cnblogs.com/chucklu/p/13048402.html
Copyright © 2011-2022 走看看