我想循环遍历服务器和端口的集合(确切地说是每个3个)并尝试建立连接,一旦建立连接,我就可以继续使用剩下的代码..这就是我的意思有
IRC_SETTINGS IRC; //3 servers & 3 ports.
foreach (string SERVER in IRC.IRC_SERVERS)
{
try
{
ircSocket = new TcpClient(SERVER, PORT);
break; //;when we have a working connection.
}
catch(Exception){}
}
我想这适用于服务器部分,但我如何同时循环访问端口?像foreach(string server,int port in ....
)答案 0 :(得分:1)
您可以将它们放入单个数据结构(例如列表)中,然后循环遍历它们:
public class IrcServer
{
public string Name { get; set; }
public int Port { get; set; }
// perhaps some methods
}
IList<IrcServer> servers = new List<IrcServer>();
foreach(IrcServer server in servers)
{
// server.Name, server.Port
}
<强>更新强>
由于您有两个不同的阵列(一个用于服务器名称,一个用于端口号),您可以合并使用它们进入字典:
int[] ports = { 1, 2, 3 };
string[] servers = { "one", "two", "three" };
var serversWithPorts = servers.
Zip(ports, (s, i) => new { s, i }).
ToDictionary(i=> i.s, i => i.i);
foreach(var server in serversWithPorts)
{
Console.WriteLine(server.Key + ":" + server.Value);
}