加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:45:47 所属栏目:百科 来源:网络整理
导读:参见英文答案 Why/when should you use nested classes in .net? Or shouldn’t you?12个 具体来说,任何人都可以给我具体的例子,何时或何时不使用嵌套类? 我永远都知道这个功能,但从来没有理由使用它. 谢谢. 解决方法 当嵌套类仅由外部类使用时,不再需要一
参见英文答案 > Why/when should you use nested classes in .net? Or shouldn’t you?12个
具体来说,任何人都可以给我具体的例子,何时或何时不使用嵌套类?

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

谢谢.

解决方法

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

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

代替

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);

这使得它不清楚什么是“真实”的意思,你可以写:

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);

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读