2012-01-25 5 views
0

문제 Adding event handler in main() for SerialPortC 번호, 회원 및 변수 범위

에 관한 것으로, 왜 메인에서 사용하지 못할?

a busy cat http://img11.imageshack.us/img11/3664/49512217.png

namespace serialport 
{ 
public class Program 
{ 


    #region Manager Variables 
    //property variables 
    private string _baudRate = string.Empty; 
    private string _parity = string.Empty; 
    private string _stopBits = string.Empty; 
    private string _dataBits = string.Empty; 
    private string _portName = string.Empty; 
    private RichTextBox _displayWindow; 
    //global manager variables 
    //private Color[] MessageColor = { Color.Blue, Color.Green, Color.Black, Color.Orange, Color.Red }; 
    internal List<Byte> portBuffer = new List<Byte>(1024); 
    private SerialPort myComPort = new SerialPort(); 
    #endregion 



    #region Manager Constructors 
    /// <summary> 
    /// Comstructor to set the properties of our 
    /// serial port communicator to nothing 
    /// </summary> 
    public Program() 
    { 
     _baudRate = string.Empty; 
     _parity = string.Empty; 
     _stopBits = string.Empty; 
     _dataBits = string.Empty; 
     _portName = "COM1"; 
     _displayWindow = null; 
     //add event handler 
     myComPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived); 
    } 
    #endregion 

    static void Main() 
    { 

     Program myProgram = new Program(); 
     //1. find available COM port 
     string[] nameArray = null; 
     string myComPortName = null; 
     nameArray = SerialPort.GetPortNames(); 
     if (nameArray.GetUpperBound(0) >= 0) 
     { 
      myComPortName = nameArray[0]; 
     } 
     else 
     { 
      Console.WriteLine("Error"); 
      return; 
     } 


     //2. create a serialport object 
     // the port object is closed automatically by use using() 
     myComPort.PortName = myComPortName; 
     //the default paramit are 9600,no parity,one stop bit, and no flow control 



     //3.open the port 
     try 
     { 
      myComPort.Open(); 
     } 
     catch (UnauthorizedAccessException ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
     //Add timeout, p161 

     //reading Bytes 
     byte[] byteBuffer = new byte[10]; 
     Int32 count; 
     Int32 numberOfReceivedBytes; 
     myComPort.Read(byteBuffer, 0, 9); 
     for (count = 0; count <= 3; count++) 
     { 
      Console.WriteLine(byteBuffer[count].ToString()); 
     } 


    } 
    //The event handler should be static?? 
    internal void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e) 
    { 
     int numberOfBytesToRead; 
     numberOfBytesToRead = myComPort.BytesToRead; 
     byte[] newReceivedData = new byte[numberOfBytesToRead]; 
     myComPort.Read(newReceivedData, 0, numberOfBytesToRead); 
     portBuffer.AddRange(newReceivedData); 
     ProcessData(); 
    } 
    private void ProcessData() 
    { 
     //when 8 bytes have arrived, display then and remove them from the buffer 
     int count; 
     int numberOfBytesToRead = 8; 

     if (portBuffer.Count >= numberOfBytesToRead) 
     { 
      for (count = 0; count < numberOfBytesToRead; count++) 
      { 
       Console.WriteLine((char)(portBuffer[count])); 
      } 
      portBuffer.RemoveRange(0, numberOfBytesToRead); 
     } 
    } 

} 

}

답변

1

Main() 있기 때문에 static 방법이다. 인스턴스 필드는 에 직접 액세스 할 수 없습니다. 메서드로을 직접 호출 할 수 없습니다. 정적 메소드는 객체의 인스턴스를 생성하거나 전달 된 객체의 인스턴스를 가져와야합니다.

+0

가 사실이 아니다! 정적 메서드에 인스턴스 (예 : 인스턴스 또는 정적 인스턴스)가 전달 된 경우에는 private 또는 not 필드에 액세스 할 수 있습니다. – jason

+0

그래서 나는 mycomport에 액세스하기 위해 재산을 사용할 것입니다. – fiftyplus

+0

@ Jason, ok하지만 그건 OP의 문제가 아닙니다. 나는 내 대답을 조정할 것이다. –

0

Mainstatic으로 선언되었으므로 private 인스턴스 필드에 액세스하려고합니다. 그럴 필요는 없으며 같은 클래스의 메서드에서만 액세스 할 수 있습니다.

오류 메시지가 표시됩니다. 그것은 말한다 :

객체 참조가 비 정적 필드, 메서드 또는 속성이 필요합니다 ....

에 "개체 참조가"당신이 인스턴스를해야한다는 것을 의미합니다.

+0

1. Main에서 정적을 제거 할 수 있습니까? 아니면 main이 기본적으로 정적입니까? – fiftyplus

+0

2. 비공개에 액세스하려면 해당 필드의 속성을 작성해야합니다. 맞습니까? – fiftyplus

+0

정적이어야합니다. 이 모든 것들을 실제로 분리 된 클래스로 분해해야합니다. – jason

0

main은 정적이므로 변수가 아닙니다.

인스턴스 변수 및 메소드는 클래스의 특정 인스턴스 (예 : new ')와 연결됩니다.

정적 변수 및 메소드는 특정 인스턴스가 아닌 클래스 유형과 연관됩니다.

나는 다음과 같은 경우 ". 인스턴스 필드 정적 메서드에 액세스 할 수 없습니다"

public class Car { 
    public int Speed { get; set; } 

    public static main(string[] args) { 
     Car a = new Car(); 
     Car b = new Car(); 

     // This is fine: 
     var aSpeed = a.Speed; 

     // This doesn't make sense (and doesn't compile) 
     // Are we talking about a's speed? b's speed? Some other car's speed? 
     var someSpeed = Speed; 

    } 

}