[英]c# cannot be referenced from a static function
c# newbie here. c#newbie here。
seems like this user gave me a very good solution for my problem: 看起来这个用户给了我一个非常好的解决方案来解决我的问题:
but i have no clue how to code up what he suggested. 但我不知道如何编码他的建议。 can you please help?
你能帮忙吗?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static SerialPort serialPort1;
public class ThreadWork
{
public static void DoWork()
{
serialPort1 = new SerialPort();
//stuff
}
}
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")));
}
}
You don't really need to have DoWork() static though. 但是,您并不需要将DoWork()静态化。
This will compile fine. 这将编译好。 You'll have to give
thePort
real settings, of course. 你必须给
thePort
真正的设置,当然。
namespace csWinFormsTest
{
public partial class Form1 : Form
{
static System.IO.Ports.SerialPort thePort;
public Form1()
{
InitializeComponent();
thePort = new System.IO.Ports.SerialPort("COM1");
}
static void fcn()
{
MessageBox.Show(thePort.PortName);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.