具体来说,有人能给我举出使用或不使用嵌套类的具体例子吗?
我一直知道这个功能,但从未有过使用它的理由。
谢谢。
具体来说,有人能给我举出使用或不使用嵌套类的具体例子吗?
我一直知道这个功能,但从未有过使用它的理由。
谢谢。
当嵌套类仅被外部类使用时,一个很好的例子是集合的枚举器类,这时可省略它。
另一个例子可能是用枚举类型替代类内方法中使用的 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);
这使得“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);
这使得客户端代码中的参数值更清晰明了。
我使用嵌套类的两个场景:
嵌套类仅被外部类使用,而我希望完全私有。
嵌套类专门用于实现在其他地方定义的接口。 例如,实现枚举器属于此类别。
我有时会用这个简单的帮助类来实现一两个函数,作为父类的一部分。
我见过嵌套类的情况,当一个特殊目的的数据结构只在一个类内使用时,或者一个特定的异常只在一个类内抛出和捕获时。
我想改进我的先前答案!
我经常使用嵌套类的特定领域是启用接口注入和控制反转。例如...
public class Worker
{
private IHelper _helper;
public Worker()
: this (new DefaultHelper())
{
}
public Worker(IHelper helper)
{
this._helper = helper;
}
private class DefaultHelper : IHelper
{
}
}
当我有一个辅助类,它不需要对系统中的任何其他对象可见时,我会嵌套类。这可以尽可能地限制可见性,有助于防止意外使用该类。
遵循 Uncle Bob 关于内聚性的“规则”会发现你实际上创建了相当多嵌套的类(甚至有嵌套的嵌套!)。这些类 可能 可以变成非嵌套的,但仅当你现在有其他客户端引用它们时。