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.

  • 相关阅读:
    随笔一
    UISegmentedControl
    adobe as3 samples
    将flash的文字转换为flash可用的矢量图
    让drawRoundRect抗锯齿的最简单的方法
    AS3和FLEX优化技巧
    Spark project 超级强大的AS3库
    API汇集
    一个as3开发人员的话
    好公司职位要求
  • 原文地址:https://www.cnblogs.com/chucklu/p/13048402.html
Copyright © 2011-2022 走看看