简体   繁体   English

无法将字典'值'复制到列表 - C#

[英]Cannot copy Dictionary 'Value' to a List - C#

Having followed a tutorial I have a hashtable that contains a TcpClient object that matches with the string of a connected user. 遵循教程我有一个哈希表,其中包含一个与连接用户的字符串匹配的TcpClient对象。 After reading about the pro's and cons of a hashtable it was recommended that using a Dictionary is preferred due to it being generic, thus more flexible. 在阅读了哈希表的原理和缺点之后,建议使用词典是首选,因为它是通用的,因此更灵活。

From here an array is made that contains the Values from the hashtable, in this case the TcpClient of the users. 从这里开始,数组包含哈希表中的值,在本例中是用户的TcpClient。 By looping the array of TcpClients I can get the stream of each user and write a message to their screen. 通过循环TcpClients数组,我可以获取每个用户的流并将消息写入其屏幕。

Now if I try and convert the array holding the TcpClient object for each user I get the following errors: 现在,如果我尝试转换为每个用户保存TcpClient对象的数组,我会收到以下错误:

The best overloaded method match for 'System.Collections.Generic.Dictionary.ValueCollection.CopyTo(System.Net.Sockets.TcpClient[], int)' has some invalid arguments 'System.Collections.Generic.Dictionary.ValueCollection.CopyTo(System.Net.Sockets.TcpClient [],int)'的最佳重载方法匹配有一些无效的参数

Argument 1: cannot convert from 'System.Collections.Generic.List' to 'System.Net.Sockets.TcpClient[]' 参数1:无法从'System.Collections.Generic.List'转换为'System.Net.Sockets.TcpClient []'

This is the Dictionary object: 这是Dictionary对象:

public static Dictionary<string, TcpClient> htUsers = new Dictionary<string, TcpClient>();

This is the List I create: 这是我创建的列表:

List<TcpClient> tcpClients = new List<TcpClient>(); 

This is the method I'm trying to follow to copy the Values to the List: 这是我试图将值复制到列表的方法:

htUsers.Values.CopyTo(tcpClients,0);

Is it something that can't be done or do I need to make a simple change? 这是不可能完成的事情还是我需要进行简单的改变?

Thanks for your time. 谢谢你的时间。

The easiest way to fix this would be to just do: 解决这个问题最简单的方法就是:

List<TcpClient> tcpClients = new List<TcpClient>(htUsers.Values);

Or: 要么:

List<TcpClient> tcpClients = new List<TcpClient>();

// Do things with list...
tcpClients.AddRange(htUsers.Values);

The CopyTo method copies into an array, not into a list. CopyTo方法复制到数组中,而不是复制到列表中。

CopyTo only copies an array to an array; CopyTo仅将数组复制到数组中; in your case, you're trying to copy an array to a list. 在您的情况下,您正在尝试将数组复制到列表中。 Try this instead: 试试这个:

List<TcpClient> tcpClients = htUsers.Values.ToList();

Note that for a lot of cases (such as enumerating), you can work directly on the dictionary: 请注意,对于很多情况(例如枚举),您可以直接在字典上工作:

foreach (var kvp in htUsers) {
    string user = kvp.Key;
    TcpClient client = kvp.Value;
    // do something
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM