Error: “an object reference is required for the non-static field, method or property…”

Error: “an object reference is required for the non-static field, method or property…”

我有一个用 C# 编写的 WPF 客户端。该程序是一个注册演示,您键入一个名称并说出它们是否在此处,然后将其发送到用户在文本框中输入的服务器和端口。

但是,当尝试在代码中应用它时,我收到错误消息:“非静态字段、方法或 属性… 需要对象引用”。 这是在 "client.connect" 行...

namespace client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }

        public class connectandsend
        {

            //if 'REGISTER' button clicked do this...{
            static void connect()
            {
                TcpClient client = new TcpClient(); // New instance of TcpClient class of the .Net.Sockets
                client.Connect(server_txt.Text, Convert.ToInt32(port_txt.Text)); // Server, Port
                StreamWriter sw = new StreamWriter(client.GetStream()); // New StreamWriter instance
                StreamReader sr = new StreamReader(client.GetStream()); // New StreamReader instance
            }

            /* static void send()
            {
                stream write... name.text and 'here' or 'not here' ticked box?
            }

            }
            */
        }

    }
}

如果您希望能够访问其中 MainWindow 的任何 non-static 成员,connect() 方法不能是 static。它也不能位于另一个 class 中,除非这个 class 或方法本身也有对 MainWindow class.

的引用

删除 static 关键字并将方法移动到 MainWindow class:

public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
    }

    void connect()
    {
        ...
    }
}

或者在调用方法时将 server_txt.Text 和 port_txt.Text 传递给该方法:

static void connect(string server, int port)
{
    TcpClient client = new TcpClient(); // New instance of TcpClient class of the .Net.Sockets
    client.Connect(server, port); // Server, Port
    StreamWriter sw = new StreamWriter(client.GetStream()); // New StreamWriter instance
    StreamReader sr = new StreamReader(client.GetStream()); // New StreamReader instance
}

主窗口:

connectandsend.connect(server_txt.Text, Convert.ToInt32(port_txt.Text));