【问题标题】:Unreachable code C#无法访问的代码 C#
【发布时间】:2014-04-29 07:59:23
【问题描述】:

执行几个 c# 循环和 if 语句。在 for 循环中突出显示无法访问的代码。我不太清楚这 1 个。

        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++ 上。任何想法为什么会这样?

【问题讨论】:

    标签: c# winforms for-loop unreachable-code


    【解决方案1】:

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

    循环不会循环

    【讨论】:

      【解决方案2】:

      原因是因为你在调用:

      return true
      

      return false
      

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

      【讨论】:

      • 为什么在循环中没有更多代码要执行时它应该给出警告?我猜 OP 显示了不同的代码。
      • @SriramSakthivel - 警告是因为编译器可以看到由于return,无论列表大小如何,它都会在一个循环后退出。因此,它“知道”如果 x = 10 它仍然只会循环一次,这可能不是预期的操作。
      • @SriramSakthivel - 需要详细说明/解释吗?如果 OP 在一个循环后是 return,如何到达 x++
      • 我的立场是正确的。现在我得到了警告是x++ 谢谢:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 2013-10-06
      • 1970-01-01
      相关资源
      最近更新 更多