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

真的吗?为什么?

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块内,请将变量初始化为null并在调用Stop之前进行检查。

修复了初始化。发现率很高的BoltClock。

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

10-11 02:03