2017-01-26 7 views
-5

C#으로 프로그래밍 된 WPF 클라이언트가 있습니다. 이 프로그램은 등록 데모이며, 이름을 입력하고 여기에 있는지 여부를 말한 다음 사용자가 텍스트 상자에 입력 한 서버와 포트로 보냅니다.오류 : "비 정적 필드, 메서드 또는 속성에 개체 참조가 필요합니다 ..."

그러나 이것을 코드에 적용하려고하면 "비 정적 필드, 메서드 또는 속성에 개체 참조가 필요합니다 ..."오류가 발생합니다. 이 당신이 그것을에 MainWindow의 비 정적 멤버에 액세스 할 수 있도록하려면

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

그는 다음을 읽으려면 시간 초과했습니다. [질문하는 방법] – MethodMan

+0

변경 내용은 충분히 만족 스럽습니다. 감사합니다. – HJagger95

답변

1

connect() 방법은 static 될 수 없습니다 ...은 "client.connect"라인에 있습니다. 또한이 클래스 나 메서드 자체에 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 
} 

을 MainWindow :

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

내가 본다면, 내 의견을 주석 처리 한 send() 메서드도 main()의 정적 멤버가 아닌 멤버에 액세스하려고 시도 할 때 send()도 무효화되어야한다고 말하는 것이 맞습니까? 처음에는 옵션으로갔습니다. – HJagger95

+0

예, 정적 메서드는 정적 인스턴스가 아닌 멤버에 액세스 할 수 없습니다. 원래 문제가 해결 되었다면 답을 수락하고 새로운 문제가있는 경우 새로운 질문을하십시오. – mm8

+0

위대한, 내 문제가 무엇인지 배울 수 있고 그것으로부터 배울 수있어서 기꺼이 받아 들였습니다. 감사! – HJagger95