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.

  • 相关阅读:
    使用docker部署zabbix
    如何用好 IDEA ,Java 撸码效率至少提升 5 倍?
    getpass模块
    linux下利用nohup后台运行jar文件包程序
    Spring Cloud 与 Dubbo 区别
    git 打标签并推送tag到托管服务器
    git-stash用法小结
    git推送本地分支到远程分支
    Git dev分支合并到master分支完美实战
    IntelliJ远程调试教程
  • 原文地址:https://www.cnblogs.com/chucklu/p/13048402.html
Copyright © 2011-2022 走看看