为什么我会永远需要使用C#的嵌套类 [英] Why Would I Ever Need to Use C# Nested Classes

查看:136
本文介绍了为什么我会永远需要使用C#的嵌套类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解有关在C#中嵌套类。我明白,一个嵌套类是在另一个类中定义的类,有什么我不明白就是为什么我会永远需要做到这一点。

I'm trying to understand about nested classes in C#. I understand that a nested class is a class that is defined within another class, what I don't get is why I would ever need to do this.

推荐答案

这是我特别喜欢的一个模式是嵌套类的工厂模式相结合:

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() { ... }
}

通过嵌套像这样的课,我使它不可能对第三方创建自己的子类。我对所有在任何的BankAccount对象运行code完全控制。和我所有的子类可以通过基类的共享实施细则。

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#的嵌套类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆