1

做一些 c# 循环和 if 语句。在 for 循环中突出显示无法访问的代码。我无法完全弄清楚这一点。

        public bool checkTime()
    {

        // Read values back from Json file
        var serializedList = File.ReadAllText(@filePathTimes);

        // getting a list of LockTime objects
        List<LockTime> deserializedList = (List<LockTime>)JsonConvert.DeserializeObject(serializedList, typeof(List<LockTime>));

        if (deserializedList.Count != 0)
        {

                // Grab whatever data you want from this list to store somewhere, such as a list of all Start and End integers.
                List<DateTime> intStartList = deserializedList.Select(entry => entry.Start).ToList();
                List<DateTime> intEndList = deserializedList.Select(entry => entry.End).ToList();

                //Then I do a foreach loop to go through every value in the start list and add the same located value to my listOfTimes (the list of LockTime objects with start and end)
                for (int x = 0; x < intStartList.Count; x++)
                {
                    TimeSpan start = new TimeSpan(intStartList[x].Hour, intStartList[x].Minute, intStartList[x].Second);
                    TimeSpan end = new TimeSpan(intEndList[x].Hour, intEndList[x].Minute, intEndList[x].Second);
                    TimeSpan now = DateTime.Now.TimeOfDay;
                    LockTime theTime = new LockTime(intStartList[x], intEndList[x]);
                    _lockTimes.Add(theTime);
                    if((now > start) && (now < end))
                    {
                        return true;
                    }

                        return false;

                }
        }
        return false;
    }

无法访问代码的亮点出现在 for 循环的 x++ 上。任何想法为什么会这样?

4

2 回答 2

11

这是因为无论发生什么,循环内的代码都会执行return true;return false;

循环不会循环

于 2014-04-29T08:00:51.033 回答
4

原因是因为您正在调用:

return true

或者

return false

在循环中,所以它总是会在转了一圈后退出。

于 2014-04-29T08:01:29.070 回答