从条件语句中获取计数

本文关键字:获取 条件 语句 | 更新日期: 2023-09-27 18:15:12

我试图使用计数变量,计算条件为真的次数,并将其用于比较。但是当我编译它时,count总是为0,它永远不会增加,即使条件为真。

foreach (ReservationType requestReservation in RequestReservation)
{
    List<String> DateList = CreateDateList(requestReservation.StartDate, requestReservation.numDays);
    foreach (Inventory inventory in RoomInventory)
    {
        if (requestReservation.hotelId == inventory.HotelId)
        {
            if (requestReservation.roomType == inventory.RoomType)
            {
                int count = 0;
                int i = 0;
                if (DateList[i] == inventory.Date && inventory.Quantity > 0)
                {
                    count++;
                    if (requestReservation.numDays == count)
                    {
                        requestReservation.reservationId = reservationid;
                        requestReservation.result = ReservationType.ReservationResultType.Success;
                        inventory.Quantity--;
                    }
                    else 
                    {
                        requestReservation.result = ReservationType.ReservationResultType.RoomNotAvailable;
                    }
                }
            }
        }                      
   }
    reservationid++;
}

从条件语句中获取计数

在循环作用域之外定义count

int count = 0;
foreach (ReservationType requestReservation in RequestReservation)
{
    List<String> DateList = CreateDateList(requestReservation.StartDate, requestReservation.numDays);
    foreach (Inventory inventory in RoomInventory)
    {
        // Rest of code
    }
}

参见microsoft.net中的变量和方法作用域-变量仅为循环作用域定义,并且在作用域结束时删除对它的任何引用。通过在循环之前定义它,它可用于外部作用域和任何嵌套作用域

请注意,当您定义:int i = 0;时,count也定义在错误的位置,您实际上总是在if语句中检查0的相同位置:

//i is always 0
if (DateList[i] == inventory.Date && inventory.Quantity > 0)

你已经在循环中声明了计数每次它都变成0在循环外声明它就会起作用

在第一次foreach循环前定义count变量