Jam*_*ing 2 c# dictionary copy list
遵循教程我有一个哈希表,其中包含一个与连接用户的字符串匹配的TcpClient对象.在阅读了哈希表的原理和缺点之后,建议使用词典是首选,因为它是通用的,因此更灵活.
从这里开始,数组包含哈希表中的值,在本例中是用户的TcpClient.通过循环TcpClients数组,我可以获取每个用户的流并将消息写入其屏幕.
现在,如果我尝试转换为每个用户保存TcpClient对象的数组,我会收到以下错误:
'System.Collections.Generic.Dictionary.ValueCollection.CopyTo(System.Net.Sockets.TcpClient [],int)'的最佳重载方法匹配有一些无效的参数
参数1:无法从'System.Collections.Generic.List'转换为'System.Net.Sockets.TcpClient []'
这是Dictionary对象:
public static Dictionary<string, TcpClient> htUsers = new Dictionary<string, TcpClient>();
Run Code Online (Sandbox Code Playgroud)
这是我创建的列表:
List<TcpClient> tcpClients = new List<TcpClient>();
Run Code Online (Sandbox Code Playgroud)
这是我试图将值复制到列表的方法:
htUsers.Values.CopyTo(tcpClients,0);
Run Code Online (Sandbox Code Playgroud)
这是不可能完成的事情还是我需要进行简单的改变?
谢谢你的时间.
解决这个问题最简单的方法就是:
List<TcpClient> tcpClients = new List<TcpClient>(htUsers.Values);
Run Code Online (Sandbox Code Playgroud)
要么:
List<TcpClient> tcpClients = new List<TcpClient>();
// Do things with list...
tcpClients.AddRange(htUsers.Values);
Run Code Online (Sandbox Code Playgroud)
该CopyTo从方法复制到一个数组,没入的列表.