<分区>
具体来说,谁能给我具体的例子说明何时或何时不使用嵌套类?
我从很久以前就知道这个功能,但从来没有理由使用它。
谢谢。
<分区>
具体来说,谁能给我具体的例子说明何时或何时不使用嵌套类?
我从很久以前就知道这个功能,但从来没有理由使用它。
谢谢。
最佳答案
当嵌套类仅由外部类使用时,一个很好的例子(不再需要)是集合的枚举器类。
另一个示例可能是用枚举替换类中方法使用的真假参数,以阐明调用签名...
代替
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/