从条件陈述中获取计数

use*_*449 3 c# c#-4.0

我正在尝试使用count变量来计算条件为真的次数,并将其用于比较.但是当我编译它时,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++;
}
Run Code Online (Sandbox Code Playgroud)

Gil*_*een 7

定义在循环范围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
    }
}
Run Code Online (Sandbox Code Playgroud)

请参阅Microsoft .NET中的变量和方法范围 - 该变量仅针对循环的范围定义,并且在范围的末尾,将删除对其的任何引用.通过在循环之前定义它,它可用于外部作用域和任何嵌套作用域

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

//i is always 0
if (DateList[i] == inventory.Date && inventory.Quantity > 0)
Run Code Online (Sandbox Code Playgroud)