C#、成员和变量作用域

本文关键字:变量 作用域 成员 | 更新日期: 2023-09-27 18:21:29

与在main()中为SerialPort 添加事件处理程序的问题有关

在我将myimport更改为类中的一个成员之后,为什么我不能主要使用它?

忙碌的猫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);
        }
    }
}

}

C#、成员和变量作用域

因为Main()static方法。实例字段不能通过static方法直接访问。静态方法必须创建对象的实例或将对象的实例传递给它才能实现。

因为Main被声明为static,但您正在尝试访问private实例字段。这是不可能的,它们只能从同一类中的方法访问。

错误消息甚至告诉你这一点。上面写着:

非静态字段、方法或属性需要对象引用。。。。

"对象引用"意味着您需要一个实例。

因为main是静态的,而现在您的变量不是。

实例变量和方法与类的一个特定实例相关联,即new'd。

静态变量和方法与类类型相关联,而不是与任何特定实例相关联。

如果我有以下内容:

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;
    }
}