You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用StreamWriter时构造函数的正确用法及跨函数调用报错解决

问题根源

你遇到的报错是变量作用域导致的:你声明的StreamWriter实例sw是Main方法内while代码块的局部变量,只在这个代码块内部可访问,Send作为独立的静态方法,自然无法直接读取到这个变量。

解决方案

这里提供两种常用的实现方式,可根据业务场景选择:

方案1:将StreamWriter作为参数传入Send方法

该方式耦合度更低,适合单次调用的场景:
修改Send方法的定义,添加StreamWriter类型的入参:

public static void Send(StreamWriter sw)
{
    sw.WriteLine("Sending this from send function");  
    sw.Flush(); // 必须调用Flush确保数据实际发送到网络流
}

在Main方法中需要调用Send的位置,把当前的sw实例传进去即可:

// 原有逻辑中调用sw.WriteLine的位置替换或追加如下代码即可
Send(sw);

方案2:将相关实例提升为类级别的静态字段

如果程序全程只维护一个TCP连接,适合用该方式,无需反复传参:
在你的Program类下直接声明静态字段:

class Program
{
    // 声明为类级别的静态字段,所有静态方法都可直接访问
    static TcpClient _client;
    static StreamWriter _sw;
    static StreamReader _sr;
    static NetworkStream _stream;

    static void Main(string[] args)
    {
        TcpListener listener = new TcpListener(System.Net.IPAddress.Any, 8081);
        listener.Start();
        Console.WriteLine("- Waiting for a connection..... .");
        _client = listener.AcceptTcpClient();
        while (true)
        {
            Console.WriteLine("Client accepted.");
            _stream = _client.GetStream();
            _sr = new StreamReader(_stream);
            _sw = new StreamWriter(_stream);
            
            // 后续原有逻辑不变
            byte[] buffer = new byte[4096];
            _stream.Read(buffer, 0, buffer.Length);
            int recv = 0;
            foreach (byte b in buffer)
            {
                if (b != 0)
                {
                    recv++;
                }
            }
            string data = Encoding.UTF8.GetString(buffer, 0, recv);
            var result = data.Split(new string[] { cr }, StringSplitOptions.None);
            System.Threading.Thread.Sleep(1000);

            _sw.WriteLine("Hello Client, This is server");
            _sw.Flush(); 
            // 直接调用Send方法即可
            Send();
        }
    }

    public static void Send()
    {
        _sw.WriteLine("Sending this from send function");  
        _sw.Flush();
    }
}
额外注意事项
  • 你当前的代码没有资源释放逻辑,长期运行可能出现内存泄漏,建议给StreamReader、StreamWriter、NetworkStream、TcpClient都加上using语句,或者在连接断开时主动调用Dispose方法释放资源
  • C#是大小写敏感的语言,方法名正确写法是WriteLine,你提供的错误代码里写的是Writeline,大小写错误也会触发编译报错

内容的提问来源于stack exchange,提问作者C noob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 17:36:03