如何在 while 循环中返回值

本文关键字:返回值 循环 while | 更新日期: 2023-09-27 17:57:14

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

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;
    }
}

如何在 while 循环中返回值

如果你想完全使用这个解决方案,你可以使用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();
        }
    }

把它包起来

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;
}