无法从静态函数引用c#

时间:2010-06-14 00:27:52

标签: c#

c#newbie here。

似乎这位用户为我的问题提供了一个非常好的解决方案:

serialport error

但我不知道如何编码他的建议。能帮忙吗?

2 个答案:

答案 0 :(得分:2)

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

你真的不需要让DoWork()静态。

答案 1 :(得分:2)

这将编译好。当然,您必须提供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);
        }
    }
}