【发布时间】:2019-03-12 11:32:22
【问题描述】:
我正在创建 2 个字符串,然后将它们存储在字典中。看来程序没有保存字符串的值。
我猜这是在我反复调用doRequest 时发生的,因为我正在创建存储在doRequest 内的字典中的变量,它只是重新创建它们。我尝试在doRequest 之外声明变量,但这似乎并没有解决我遇到的问题。
在方法之外声明变量并做错了,我是否走在正确的轨道上,还是有更好的方法来存储变量?
public class Respond
{
static void Main(string[] args)
{
RunServer();
}
//public static string user = null;
//public static string location = null;
static void RunServer()
{
TcpListener listener;
Socket connection;
NetworkStream socketStream;
try
{
listener = new TcpListener(IPAddress.Any, 43);
listener.Start();
Console.WriteLine("server is listening");
while (true)
{
connection = listener.AcceptSocket();
socketStream = new NetworkStream(connection);
Console.WriteLine("connection received");
DoRequest(socketStream);
socketStream.Close();
connection.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.ToString());
}
}
static void DoRequest(NetworkStream socketStream)
{
Hashtable userPlusLocation = new Hashtable();
Dictionary<string, string> userPlusLocation2 = new Dictionary<string, string>();
//string user = null;
//string location = null;
//userPlusLocation.Add(user, location); //user = key , location = value
StreamWriter sw = new StreamWriter(socketStream);
StreamReader sr = new StreamReader(socketStream);
string line = sr.ReadLine().Trim();
Console.WriteLine("respond received: " + line);
string[] sections = line.Split(new char[] { ' ' }, 2);
try
{
//write if statements for user and location inputs
if (user == null)
{
user = sections[0];
userPlusLocation2.Add(user, location);
}
if (sections.Length == 1)
{
sw.WriteLine(userPlusLocation2[user]);
sw.Flush();
Console.WriteLine("single arg received");
Console.WriteLine("location: " + userPlusLocation2[user]);
}
else
{
location = sections[1];
userPlusLocation2[user] = location;
sw.WriteLine("OK");
sw.Flush();
Console.WriteLine("location: " + userPlusLocation2[user]);
}
}
catch(Exception e)
{
sw.WriteLine("error stuff: " + e);
}
}
}
【问题讨论】:
-
这
if (user == null)不是应该是if (user != null)吗? -
在方法之外声明变量并做错了,我是否走在正确的轨道上? 是的,将您的字典移至类级别并使其成为静态。拆分输入后,不要问user是否为null;相反,请询问您的字典是否已经有该键。
-
@mjwills 将
userPlusLocation2.Add(user, location);移到了if语句之外,没有任何变化
标签: c# string dictionary