我在类中有以下代码来设置串口甚至处理程序。
我得到两个警告; CA1034(不要嵌套类型),它告诉我让我的delgate私有(这将阻止我在继承的类中设置偶数处理程序)和CA1009(将事件的第二个参数声明为EventArgs,或者实例为一个扩展EventArgs的类型,名为' e'),我不明白。
我的代码在
下面myPort.DataReceived += new SerialDataReceivedEventHandler(port_OnDataRecived); //Setup when port is opened
private void port_OnDataRecived(object sender, SerialDataReceivedEventArgs e)
{
int lengthToRead = myPort.BytesToRead;
byte[] rxBytes = new byte[lengthToRead];
myPort.Read(rxBytes, 0, lengthToRead);
PacketReceived(rxBytes, e);
}
public delegate void PacketReceivedEventHandler(object sender, byte[] packet);
public event PacketReceivedEventHandler OnPacketReceived;
public virtual void PacketReceived(byte[] packet, EventArgs e)
{
if (OnPacketReceived != null)
{
OnPacketReceived(this, packet);
}
}
我一直在查看MSDN文章和一些SO问题,但我无法将建议的修复程序与我自己的代码联系起来。 This answer有点合理,但转换我的代码看起来会导致
OnPacketReceived(this, packet);
替换为
handle(this, new PacketReceivedEventHandler();
带有一个参数(void (object, byte[]) target)
(我被卡住的地方)。至于尝试修复CA1034警告,我甚至不知道我写的是嵌套类型,MSDN文章中没有包含如何修复规则违规的示例。
答案 0 :(得分:5)
我甚至不知道我写的是嵌套类型
您已在班级中声明了自己的代理人类型(PacketReceivedEventHandler
)。那个类型嵌套在另一个类型中。只需将声明移到现有的类声明之外。
对于其他警告,您要创建一个PacketEventArgs
类,该类派生自EventArgs
并包含数据包数据作为额外属性。此时,您可以使用EventHandler<PacketEventArgs>
而不是声明自己的委托。
此外:
PacketReceived
,您的方法将为OnPacketReceived
(并受到保护),而不是相反。有了这一切,你就拥有了:
public event EventHandler<PacketEventArgs> PacketReceived;
protected virtual void OnPacketReceived(byte[] packet)
{
var handler = PacketReceived;
if (handler != null)
{
handler.Invoke(this, new PacketEventArgs(packet));
}
}
或者在C#6中,使用空条件运算符使实现更简单:
public event EventHandler<PacketEventArgs> PacketReceived;
protected virtual void OnPacketReceived(byte[] packet)
{
PacketReceived?.Invoke(this, new PacketEventArgs(packet));
}