2017-01-26 58 views
-5

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

      } 
      */ 
     } 

    } 
} 
+2

请把t他超时阅读以下内容 [如何提出问题](http://stackoverflow.com/help/how-to-ask) – MethodMan

+0

做出了改变,希望它足够好,谢谢。 – HJagger95

回答

1

connect()方法不能是static,如果你希望能够访问MainWindow的任何非静态成员在里面。除非这个类或方法本身也提及MainWindow类,否则它不能位于另一个类中。

取出static关键字和移动的方法对MainWindow类:

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)); 
+0

我明白了,我说的我的注释,send()方法应该也是void send(),因为它也试图访问mainwindow的非静态成员?顺便说一句,我用第一个选项去了。 – HJagger95

+0

是的,没有静态方法可以访问任何非静态实例成员。如果您的原始问题已解决,请记住接受答案,如果您有新问题,请提出新问题。 – mm8

+0

太棒了,很高兴我能够知道我的问题是什么,并从中学习,答案接受。谢谢! – HJagger95

相关问题