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

Joh*_*ski 9 c# class-design nested class nested-class

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

我永远都知道这个功能,但从来没有理由使用它.

谢谢.

Cha*_*ana 16

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

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

代替

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

  product P = new Product();
  int TotalInventory = P.AmountInInventory(123, true);  
Run Code Online (Sandbox Code Playgroud)

这让人不清楚"真实"意味着什么,你可以这样写:

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);  
Run Code Online (Sandbox Code Playgroud)

这使得客户端代码中的参数值清晰.


Ree*_*sey 11

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

  • 嵌套类由外部类专门使用,我想要完全私有范围.

  • 嵌套类专门用于实现其他地方定义的接口.例如,实现枚举器属于此类别.