错误:“非静态字段,方法或属性需要对象引用......”

时间:2017-01-26 19:17:03

标签: c# wpf object-reference

我有一个用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?
            }

            }
            */
        }

    }
}

1 个答案:

答案 0 :(得分:1)

如果您希望能够访问其中q)t1b:([Symbol:`000001.SZ`000001.ZK`000002.SZ`000002.ZK`000004.SZ]RIC:`000001.SZ`000001.ZK`000002.SZ`000002.ZK`000004.SZ) q)t2b:([Symbol:`1301`1332`1333`1334`1352]RIC:`1301.T`1332.T`1333.T`1334.T`1352.T) q)meta t1b c | t f a ------| ----- Symbol| s RIC | s q)meta t2b c | t f a ------| ----- Symbol| s RIC | s q)keys t1b ,`Symbol q)keys t2b ,`Symbol q)t1b uj t2b Symbol | RIC ---------| --------- 000001.SZ| 000001.SZ 000001.ZK| 000001.ZK 000002.SZ| 000002.SZ 000002.ZK| 000002.ZK 000004.SZ| 000004.SZ 1301 | 1301.T 1332 | 1332.T 1333 | 1333.T 1334 | 1334.T 1352 | 1352.T q)t1b Symbol | RIC ---------| --------- 000001.SZ| 000001.SZ 000001.ZK| 000001.ZK 000002.SZ| 000002.SZ 000002.ZK| 000002.ZK 000004.SZ| 000004.SZ q)t2b Symbol| RIC ------| ------ 1301 | 1301.T 1332 | 1332.T 1333 | 1333.T 1334 | 1334.T 1352 | 1352.T 的任何非静态成员,则connect()方法不能为static。此外,它不能位于另一个类中,除非此类或方法本身也具有对MainWindow类的引用。

删除MainWindow关键字并将方法移至static类:

MainWindow

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

public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
    }

    void connect()
    {
        ...
    }
}

<强>主窗口:

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
}