串口在当前上下文中不存在:c#

时间:2010-06-14 01:00:03

标签: c#

这是代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public class ThreadWork
        {
            private static SerialPort serialPort1;
            public static void DoWork()
            {
                serialPort1.Open();
                serialPort1.Write("AT+CMGF=1\r\n");
                //Thread.Sleep(500);
                serialPort1.Write("AT+CNMI=2,2\r\n");
                //Thread.Sleep(500);
                serialPort1.Write("AT+CSCA=\"+4790002100\"\r\n");
                //Thread.Sleep(500);
                serialPort1.DataReceived += serialPort1_DataReceived_1;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ThreadStart myThreadDelegate = new ThreadStart(ThreadWork.DoWork);
            Thread myThread = new Thread(myThreadDelegate);
            myThread.Start();
        }

        private void serialPort1_DataReceived_1(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            string response = serialPort1.ReadLine();
            this.BeginInvoke(new MethodInvoker(() => textBox1.AppendText(response + "\r\n")));
        }
    }
}

我在这一行收到错误:

string response = serialPort1.ReadLine();

它说::

错误1当前上下文中不存在名称“serialPort1”C:\ Users \ alexluvsdanielle \ AppData \ Local \ Temporary Projects \ WindowsFormsApplication1 \ Form1.cs 44 31 WindowsFormsApplication1

我做错了什么?

2 个答案:

答案 0 :(得分:1)

serialPort1的定义向上移动到Form1类,而不是Form1.ThreadWork类。

目前,在Form1.ThreadWork课程中,它只能由Form1.ThreadWork课程的成员看到,而不是Form1课程。

答案 1 :(得分:1)

serialport1存在于ThreadWork类中,而不是表单