c# - 限制 2 个单独列表的组合计数 - C#

标签 c# list count

我在 Visual C# 项目中有以下类:

    public class Bus
    {
    private int BusNumber;
    public int busNumber
    {
        get { return BusNumber; }
        set { BusNumber = value; }
    }

    public List<CircularRoute> circularRoute = new List<CircularRoute>();
    public List<LongDistance> longDistance = new List<LongDistance>();
    }

有什么方法可以限制两个列表的总和?我知道如果我使用多态列表,我可以使用 if 语句轻松地做到这一点。不过目前这不是我的选择。

最佳答案

不要将列表公开为公开 - 将它们保密并提供添加到每个列表的方法。

在这些方法中,您可以检查两个列表的计数,并且仅在它们低于您的阈值时才添加。

如果您需要公开列表,我建议返回这些私有(private)列表的副本(使用复制构造函数),这样就不会违反不变量。

private List<CircularRoute> circularRoute = new List<CircularRoute>();

public AddRoute(CircularRoute route)
{
  if(circularRoute.Count + longDistance.Count < threshold)
  {
    // add logic.
  }
  else
  {
    // Perhaps throw an exception
  }
}

public IEnumerable<CircularRoute> CircularRoutes
{
   get { return new List<CircularRoute>(circularRoute); }
}

关于c# - 限制 2 个单独列表的组合计数 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13700842/

相关文章:

mysql - 计算 SQL 中计数相对于类别的百分比

c# - 计算 Int32 中的前导零

c# - Azure 移动服务客户端 - 在多个 InsertAsync 任务上使用 WaitAll

c# - 使用 HttpClient 时如何在 HttpContent 中设置大字符串?

python - 通过将列表索引视为python中的键,将dict中的所有列表转换为dict

python - 为什么 remove() 实际上不删除 Python 列表中重复项的最后一个实例

MySQL ROUND() 计算错误

c# - 是否可以从后面的代码编辑元描述?

c# - 如何使用属性名称和前缀从属性方面调用特定方法?

python - 列表,元组和统计程序尝试-除 block 错误