我正在尝试使用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++;
}
答案 0 :(得分:7)
在循环的scope之外定义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
}
}
参见Variable and Method Scope in Microsoft .NET - 变量仅针对循环的范围定义,并且在范围的末尾删除对它的任何引用。通过在循环之前定义它,它可用于外部作用域和任何嵌套作用域
请注意,当你定义count
时,int i = 0;
定义错误,你实际上总是在你的if语句中检查0
的相同位置:
//i is always 0
if (DateList[i] == inventory.Date && inventory.Quantity > 0)
答案 1 :(得分:1)
你已经在循环中声明了计数,并且每次将它声明出循环并且它将会起作用时它变为0
答案 2 :(得分:1)
在第一个foreach循环之前定义计数变量。