你什么时候想在 C# 中嵌套类?

发布于 2024-08-05 06:14:31 字数 81 浏览 2 评论 0原文

具体来说,任何人都可以给我何时或何时不使用嵌套类的具体示例吗?

我一直都知道这个功能,但从来没有理由使用它。

谢谢。

Specifically, can anyone give me concrete examples of when or when not to use nested classes?

I've known about this feature since forever, but never had a reason to use it.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

心是晴朗的。 2024-08-12 06:14:31

当嵌套类仅由外部类使用时,一个很好的例子(不再需要)是集合的枚举器类。

另一个例子可能是用枚举替换类中方法使用的 true false 参数,以澄清调用签名...

而不是

public class Product
{
    public void AmountInInventory(int warehouseId, bool includeReturns)
    {
        int totalCount = CountOfNewItems();
        if (includeReturns)
            totalCount+= CountOfReturnedItems();
        return totalCount;
    }
}

and

  product P = new Product();
  int TotalInventory = P.AmountInInventory(123, true);  

含义,您可以编写:

public class Product
{
    [Flags]public enum Include{None=0, New=1, Returns=2, All=3 }
    public void AmountInInventory(int warehouseId, Include include)
    {
        int totalCount = 0;
        if ((include & Include.New) == Include.New)
            totalCount += CountOfNewItems();
        if ((include & Include.Returns) == Include.Returns)
            totalCount += CountOfReturns();
        return totalCount;
    }
}


  product P = new Product();
  int TotalInventory = P.AmountInInventory(123, Product.Include.All);  

这使得不清楚“true”的 参数值在客户端代码中明确。

When the nested class is only used by the outer class, a great example, no longer necessary, is for an enumerator class for a collection.

another example might be for a enum to replace a true false parameter used by a method within a class, to clarify the call signature...

instead of

public class Product
{
    public void AmountInInventory(int warehouseId, bool includeReturns)
    {
        int totalCount = CountOfNewItems();
        if (includeReturns)
            totalCount+= CountOfReturnedItems();
        return totalCount;
    }
}

and

  product P = new Product();
  int TotalInventory = P.AmountInInventory(123, true);  

which leaves it unclear as to what 'true' means, you could write:

public class Product
{
    [Flags]public enum Include{None=0, New=1, Returns=2, All=3 }
    public void AmountInInventory(int warehouseId, Include include)
    {
        int totalCount = 0;
        if ((include & Include.New) == Include.New)
            totalCount += CountOfNewItems();
        if ((include & Include.Returns) == Include.Returns)
            totalCount += CountOfReturns();
        return totalCount;
    }
}


  product P = new Product();
  int TotalInventory = P.AmountInInventory(123, Product.Include.All);  

Which makes the parameter value clear in client code.

忆梦 2024-08-12 06:14:31

我使用嵌套类的两个地方:

  • 嵌套类由外部类独占使用,我想要完全私有的作用域。

  • 嵌套类专门用于实现其他地方定义的接口。例如,实现一个枚举器就属于这一类。

The two places where I use nested classes:

  • The nested class is used exclusively by the outer class, and I want completely private scope.

  • The nested class is used specifically to implement an interface defined elsewhere. For example, implementing an enumerator falls into this category.

日裸衫吸 2024-08-12 06:14:31

当您确定嵌套类在其他任何地方使用没有意义时,您实际上只想使用嵌套类。

例如,如果您需要创建一个由多种类型的对象组成的列表,这些对象与该组对象的函数和成员信息(例如方法或属性)在短时间内关联在一起,则可以使用嵌套类来执行此操作。也许您需要创建某种类型对象的所有组合的列表,然后标记具有特定属性的所有组合。这对于嵌套类来说是一个很好的例子。

如果您不需要嵌套类上的方法,您可能可以只使用 struct 但我不知道 IL 是否会以不同的方式对待它们。

You really only want to use nested classes when you are sure the nested class doesn't make sense that it would be used anywhere else.

For example, if you needed to create a list of several types of object associated together with functions and member information about that set of objects for a short time (like methods or properties), you could use a nested class to do that. Maybe you need to create a list of all combinations of some type of object, and then mark all combinations that have a certain property. That would be a good case for a nested class.

If you don't need methods on the nested class, you can probably just use a struct but I don't know if IL treats them any differently.

梦回梦里 2024-08-12 06:14:31

我有时将其用于简单的辅助类,我需要父类内部的一个或两个函数。

I sometimes use this for simple helper classes that I need for a function or two inside of the parent class.

深居我梦 2024-08-12 06:14:31

有关实际示例,请参阅今天早上早些时候提出的这个问题:
使对象只能访问同一程序集中的另一个对象?

摘要:您可以在其业务对象中嵌套关联的数据类。

For a practical example, see this question asked earlier this morning:
Make an object accessible to only one other object in the same assembly?

Summary: you can nest an associated data class inside it's business object.

魔法唧唧 2024-08-12 06:14:31

我见过嵌套类的情况,即仅在一个类中使用特殊用途的数据结构,或者仅在一个类中抛出并捕获特定异常。

I've seen cases of nested classes when a special purpose data structure is used only within one class, or a certain exception is thrown and caught only within one class.

凉城 2024-08-12 06:14:31

当我有一个不需要对系统中的任何其他对象可见的辅助类时,我会嵌套类。这使可见性尽可能受到限制,这有助于防止该类的意外使用

I nest classes when I have a helper class which has no need to be visible to any other object in the system. This keeps the visibility as constrained as possible which helps prevent unintended uses of the class

送舟行 2024-08-12 06:14:31

遵循鲍勃叔叔关于内聚性的“规则”应该会发现您实际上创建了相当多的嵌套(并且嵌套,嵌套!)类。这些可以设为非嵌套,但如果您现在有其他客户端引用它们。

Following Uncle Bob's 'rules' on cohesion should find that you actually create quite a number of nested (and nested, nested!) classes. These could be made non-nested but only if you have other clients that reference them now.

坚持沉默 2024-08-12 06:14:31

我想改进我之前的答案!

我经常使用嵌套类的一个特定领域是启用接口注入和控制反转。例子...

public class Worker
{
  private IHelper _helper;

  public Worker()
    : this (new DefaultHelper())
  {
  }
  public Worker(IHelper helper)
  {
    this._helper = helper;
  }

  private class DefaultHelper : IHelper
  {
  }
}

I'd like to improve on my previous answer!

A specific area where I use nested classes regularly is enabling Interface Injection and Inversion of Control. Example...

public class Worker
{
  private IHelper _helper;

  public Worker()
    : this (new DefaultHelper())
  {
  }
  public Worker(IHelper helper)
  {
    this._helper = helper;
  }

  private class DefaultHelper : IHelper
  {
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文