2017-08-16 129 views
-3

for-loop内部的内容可以正常工作,但是在循环运行后,PingTimes -list始终为空。这里发生了什么?这里对于C#来说很新颖。Ping.Send为什么不在for循环中工作?

 private void PingTest() 
    { 
     List<long> PingTimes = new List<long>(); 
     Ping PingSender = new Ping(); 
     PingOptions options = new PingOptions(); 

     options.DontFragment = true; 

     string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; 
     byte[] buffer = Encoding.ASCII.GetBytes(data); 
     int timeout = 120; 


     for (int i = 1; i >= TimesToPing; i++) 
     { 
      PingReply reply = PingSender.Send(PingAddress, timeout, buffer, options); 
      if (reply.Status == IPStatus.Success) 
      { 
       PingTimes.Add(reply.RoundtripTime); 
      } 
      else 
      { 
       MessageBox.Show("Ping test failed due to an unknown reason."); 
       break; 
      } 
     } 
     MessageBox.Show("Pinged Address: " + PingAddress + "\nAverage Ping: " + PingTimes.Average().ToString() + "ms"); 
    } 
+2

在计算机科学硕士真的应该知道如何使用_debugger_ – MickyD

回答

4

您的循环条件被反转,所以循环将永远不会运行。 :)

+1

这是如此的耻辱。 – Ricochet

+0

@Ricochet只是一个提示,我并不是说这是一个家伙,但是当一个循环不行为时,在循环内部放置一个打印,以确保循环本身按照您的预期运行。 – Carcigenicate