控制台程序,静态方法,套接字变为空

时间:2013-08-26 16:51:45

标签: c# .net static static-methods static-members

class Program
{
    static Socket m_sock;

    static void Main(string[] args)
    {
        Socket m_sock= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        .
        .
        .
        m_sock.Connect(ipendLocalhost);
        SendRequest("command");
    }

    static void SendRequest(string sCommand)
    {
       .
       .
     **m_sock.Send(szCommand, iBytesToSend, SocketFlags.None);**
     }

说到Send方法,我得到NullReferenceException。在调试中(我添加了m_sock来监视)我看到当程序进入SendRequest方法时,m_sock变为null。我不明白为什么会这样,问题出在哪里。请帮忙。

3 个答案:

答案 0 :(得分:2)

m_sock是在Main和class级别内部定义的,您不必在Main中再次定义它,只需初始化它,如:

static void Main(string[] args)
    {
        m_sock= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

请注意Socket已删除。

目前,您的Main方法正在初始化本地m_sock,这就是您的类级m_sock保持为空的原因,稍后当您在静态方法中访问它时,您将获得异常。

答案 1 :(得分:2)

因为您在Main

中声明了另一个m_sock
Socket m_sock=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

将其更改为

m_sock=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

答案 2 :(得分:2)

问题来自您在Main中的声明,Socket m_sock=隐藏了类级别的字段。

static Socket m_sock;
static void Main(string[] args)
{
    Socket m_sock = new Socket // Create a new Socket in m_sock from the Main method only
    SendRequest("command");
}

static void SendRequest(string sCommand)
{
  m_sock.Send() // Uses the socket at the Class level, which is not initialized
}

将初始化更改为

static void Main(string[] args)
{
    m_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    m_sock.Connect(ipendLocalhost);

    SendRequest("command");
}

或删除类级别声明并将其作为变量传递

static void Main(string[] args)
{
    Socket m_sock= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    m_sock.Connect(ipendLocalhost);

    SendRequest(m_sock, "command");
}

static void SendRequest(Socket m_sock, string sCommand)
{
   m_sock.Send(szCommand, iBytesToSend, SocketFlags.None);
}