我正在写一个数据接收事件对于串行IO端口......以下是代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO; //add namespaces
using System.IO.Ports;
public class Program
{
//define a delegate class to handle DataReceived events
internal delegate void SerialDataReceivedEventHanderDelegate(object sender,SerialDataReceivedEventArgs e);
internal void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//place code to read and process data here
}
static void Main()
{
string myComPortName=null;
//1. find available COM port
string[] nameArray = 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()
SerialPort myComPort = new SerialPort();
myComPort.PortName = myComPortName; //the default paramit are 9600,no parity,one stop bit, and no flow control
private static SerialDataReceivedEventHandler SerialDataReceivedEventHandler1 =
new SerialDataReceivedEventHandler(ComPort.DataReceived);
myComPort.DataReceived+=SerialDataReceivedEventHandler1;
}
}
为什么在VS2010中,Line: private static SerialDataReceivedEventHandler SerialDataReceivedEventHandler1 = new SerialDataReceivedEventHandler(ComPort.DataReceived);
告诉我: 1.无效表达术语'私人' 2.修饰符'static'对此术语无效 3.我应该在这里使用Comport吗?或者只是DataReceived ...因为它的函数名称
感谢您的回复。
答案 0 :(得分:2)
private
和static
在方法范围内无效。
您只能在类级别声明静态项目 - 即此处:
public class Program
{
private static object _memberField;
private static void MemberMethod()
{
// not here:
// private static object _insideMethod; // <- will not work
}
}
答案 1 :(得分:1)
不需要私有静态,只需: -
var SerialDataReceivedEventHandler1 =
new SerialDataReceivedEventHandler(ComPort.DataReceived);
但如果您希望成为Program类的成员,请将声明移至: -
public class Program
{
private static SerialDataReceivedEventHandler;
然后你需要在Main
SerialDataReceivedEventHandler1 =
new SerialDataReceivedEventHandler(ComPort.DataReceived);
但更有可能的是,你真的想要开始自己的类,因为“程序”并不是真正最好的地方....而处理静态类和静态方法有点凌乱
答案 2 :(得分:0)
private
用于控制类型成员的可访问性或类型本身。它不适用于作为方法一部分的变量,因为它已经是方法本身最容易访问的。
此外,静态修饰符也无效。它也适用于类型的成员,以指示该成员是否可识别实例。
你的专栏:
private static SerialDataReceivedEventHandler SerialDataReceivedEventHandler1 =
new SerialDataReceivedEventHandler(ComPort.DataReceived);
应该是:
SerialDataReceivedEventHandler SerialDataReceivedEventHandler1 =
new SerialDataReceivedEventHandler(ComPort.DataReceived);
然而,这条线似乎完全没必要。您可以将其简化为:
myComPort.DataReceived += ComPort.DataReceived;
答案 3 :(得分:0)
该行位于main方法内。私有和静态只允许在方法之外。
答案 4 :(得分:0)
private限定符仅适用于类定义中的成员(成员变量/方法)。 SerialDataReceivedEventHandler只是一个方法中的变量。