2015-06-21 237 views
0

我有一个方法,返回类型是List<User>。在这个方法中,我有无限的while循环通过套接字接受来自另一个客户端的信息。一旦新客户接受,我会将此用户添加到列表中,并继续收听新客户。我给这个方法的构造。假设接受多个客户。现在,只允许我接受一个客户。之前,我们没有将类型设置为List<User>,然后没有return UserList,并且整个代码对多个用户都正常工作。添加返回类型的Method后,它不起作用。如何在while循环中返回一个值

public List<User> accept() { 
    List<User> userList = new List<User>(); 
    while (true) { 
     Command_Listening_Socket = server.Accept(); 

     int msgLenght = Command_Listening_Socket.Receive(msgFromMobile);// receive the byte array from mobile, and store into msgFormMobile 
     string msg = System.Text.Encoding.ASCII.GetString(msgFromMobile, 0, msgLenght);// convert into string type 

     if (msg == "setup") { 
      my_user = new User(); 
      userList.Add(my_user); 
     } 
     return userList; 
    } 
} 
+2

回报用户列表,而不是在UserList? (大写字母) – Bob

+0

不,类型错误 –

+0

如果没有返回,退出条件是什么? – Ediac

回答

2

如果你想使用的正是这种解决方案可以使用的,而不是yield return声明return

但是你需要遍历Accept()方法的结果。

但是对这种类型的代码结构使用基于事件的解决方案是很好的。

public class Program 
    { 
     public static IEnumerable<object> Accept() 
     { 
      var userList = new List<object>(); 
      var index = 0; 
      while (true) 
      { 
       var msg = "setup"; 
       if (msg == "setup") 
       { 
        var returnUser = new 
        { 
         Name = "in method " + index 

        }; 
        Thread.Sleep(300); 
        yield return returnUser; 
       } 
       index++; 
      } 
     } 

     private static void Main(string[] args) 
     { 
      foreach (var acc in Accept()) 
      { 
       Console.WriteLine(acc.ToString()); 
      } 
      Console.WriteLine("Press any key to continue."); 
      Console.ReadLine(); 
     } 
    } 
-1

就包起来

public void accept() 
{ 
    List<User> users = new List<User>(); 

    while (true) 
    { 
     var user = _accept() 

     if(user != null) 
     { 
      users.Add(user) 
     } 
    } 
} 

public User _accept() 
{ 
     User my_user = null; 

     Command_Listening_Socket = server.Accept(); 

     int msgLenght = Command_Listening_Socket.Receive(msgFromMobile);// receive the byte array from mobile, and store into msgFormMobile 
     string msg = System.Text.Encoding.ASCII.GetString(msgFromMobile, 0, msgLenght);// convert into string type 

     if (msg == "setup") 
     { 
      my_user = new User(); 
     } 

     return my_user; 
}