数组维度超出支持的范围,.NET API

6yoyoihd  于 2023-11-20  发布在  .NET
关注(0)|答案(1)|浏览(180)

可以在TimeOnly类型上循环吗?我正在尝试使用while循环创建List<TimeOnly>

[HttpPost]
public async Task<ActionResult<Shedule>> CreateNewShedule(SheduleCreateDto sheduleCreateDto)
{
    

    var hours = new List<TimeOnly>{};
    var startHour = TimeOnly.Parse(sheduleCreateDto.StartHour);
    var endHour = TimeOnly.Parse(sheduleCreateDto.EndHour);

    while(!startHour.Equals(endHour)){
        hours.Add(startHour);
        startHour.AddMinutes(15);
    }

    var shedule = new Shedule
    {
        WeekDay = sheduleCreateDto.WeekDay,
        VisitTime = sheduleCreateDto.VisitTime,
        Hours = hours
    };

    _context.Shedules.Add(shedule);
    if( await _context.SaveChangesAsync() > 0) return Ok(shedule);

    return BadRequest("Failed to add shedule");
}

字符串
当我发布请求时,它看起来像是无限循环,然后我得到了这样的错误:

数组维数超出支持范围。

当我使用for循环和

cig3rfwq

cig3rfwq1#

主要问题是TimeOnly.AddMinutes返回一个新的TimeOnly(因为你不能修改它)。所以你必须把它赋给变量startHour

startHour = startHour.AddMinutes(15);

字符串
下一个问题是startHour可能永远不等于endHour。所以使用<

while(startHour < endHour)
{
    hours.Add(startHour);
    startHour = startHour.AddMinutes(15);
}


你还应该首先确保你有有效的时间,所以结束应该在开始之后:

var startHour = TimeOnly.Parse(sheduleCreateDto.StartHour);
var endHour = TimeOnly.Parse(sheduleCreateDto.EndHour);
bool valid = endHour > startHour; // handle invalid now and don't start processing

相关问题