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

标签 c# class class-design nested-class nested

<分区>

具体来说,谁能给我具体的例子说明何时或何时不使用嵌套类?

我从很久以前就知道这个功能,但从来没有理由使用它。

谢谢。

最佳答案

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

另一个示例可能是用枚举替换类中方法使用的真假参数,以阐明调用签名...

代替

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

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

这使得“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);  

这使得参数值在客户端代码中清晰可见。

关于c# - 你什么时候想在 C# 中嵌套类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1427967/

相关文章:

c++ - 对类构造函数进行单元测试

java - 是否可以找到对象的实例而不将其传递给方法?

c# - 在sql server中获取唯一值

c# - 在 ElasticSearch 5.5 中使用摄取插件时如何获取术语向量?

c# - 在 C# 中运行 cmd

c# - ASP.NET/C# : Bundling Sets of Files, 压缩它们,并通过响应发送回用户

java - 如何从 C 中加载和调用 java 编译的类?

c++ - 将对象存储在 vector 中,编译器说元素不存在

design-patterns - 用户登录的 UML 类图

oop - "is A"VS "is Like A"关系,每一个的含义是什么以及它们有何不同?