【发布时间】:2025-12-21 13:20:16
【问题描述】:
我有以下代码:
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
{
public static void DoWork()
{
serialPort1 = new SerialPort();
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")));
}
}
}
对于所有serialport1 行,我都收到此错误:
错误 1 非静态字段、方法或属性“WindowsFormsApplication1.Form1.serialPort1”需要对象引用 C:\Users\alexluvsdanielle\AppData\Local\Temporary Projects\WindowsFormsApplication1\Form1.cs 23 17 WindowsFormsApplication1
我做错了什么?
【问题讨论】:
-
你“新”了一个串口吗?
-
serialPort1 声明在哪里?
-
是的,我确实声明了它,但仍然说了同样的话
标签: c#