c# - 更改字典中的值不保存在循环方法中
问题描述
我正在创建 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);
}
}
}
解决方案
如果您想保留 hastable 和字典值,您还需要在 doRequest 方法之外声明它们。
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
doRequest 中的上述代码块创建了仅对 doRequest 方法本地的变量,因此一旦方法完成,变量也是如此。要解决此问题,请在方法之外声明您需要的所有内容。并注意不要重新声明它
= new stufff
在你完成之前,因为这会覆盖你的值。
推荐阅读
- recursion - 如何从方案中的列表中制作 HTML,球拍
- r - 选择功能有问题。不断添加我不想在数据框中包含的列
- python - 即使输入数据是数字,带有 dtype=pd.CategoricalDtype() 的 Pandas 的 read_csv 也会创建“对象”类别
- ios - 如何检测 SKPaymentTransaction 何时中断?
- c# - OnPrem IIS 上传和提供图像
- batch-file - 在批处理文件中使用 echo
- java - org.apache.wicket.markup.MarkupNotFoundException:未找到组件的标记:[TreeTableItem [组件 id = 0]]
- javascript - JS中可以自动出现空值吗
- nginx - 在 nginx-rtmp 上直播后未调用 exec_record_done
- mongodb - 如何根据一段字符串过滤集合