gpt4 book ai didi

c# - 为什么我在本地声明的变量在 finally block 中没有被识别?

转载 作者:行者123 更新时间:2023-11-30 18:50:35 25 4
gpt4 key购买 nike

通过下面的代码,我得到:“名称‘listener’在当前上下文中不存在”

真的吗?为什么?

static void ReceiveSocketMsgs()
{
try
{
TcpListener listener;
listener = new TcpListener(IPAddress.Any, MainForm.GOHRFTrackerMainForm.socketPortNum);
listener.Start();
using (TcpClient c = listener.AcceptTcpClient())
{
using (NetworkStream n = c.GetStream())
{
string msg = new BinaryReader(n).ReadString();
BinaryWriter w = new BinaryWriter(n);
w.Write(msg + " received");
w.Flush(); // Must call Flush because we're not disposing the writer.
}
}
}
catch (Exception ex)
{
//some exception (if you close the app, it will be "threadabort")
}
finally
{
listener.Stop();
}
}

最佳答案

这就是 C# 作用域的工作原理。它确实妨碍了 lock 语句和 try/catch 子句。只需将声明移到外面:

static void ReceiveSocketMsgs()
{
TcpListener listener = null;
try
{
listener = new TcpListener(IPAddress.Any, MainForm.GOHRFTrackerMainForm.socketPortNum);
...
}
catch (Exception ex)
{
//some exception (if you close the app, it will be "threadabort")
}
finally
{
if (listener != null)
listener.Stop();
}
}

要将监听器初始化保持在 try block 内,请将变量初始化为 null 并在调用 Stop 之前检查它。

修复了初始化。很好地发现了 BoltClock。

关于c# - 为什么我在本地声明的变量在 finally block 中没有被识别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8857066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com