我在类中有以下代码来设置串行端口甚至处理程序.
我得到两个警告; 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问题,但我无法将建议的修复程序与我自己的代码联系起来. 这个答案是有道理的,但转换我的代码看起来像它导致
OnPacketReceived(this, packet);
被替换为
handle(this, new PacketReceivedEventHandler();
这是一个争论(void (object, byte[]) target)
(这是我被困的地方).至于尝试修复CA1034警告,我甚至看不到我写的是嵌套类型,MSDN文章没有包含如何修复规则违规的示例.
我甚至不知道我写的是嵌套类型
您已PacketReceivedEventHandler
在类中声明了委托类型().这是嵌套在另一个内部的一种类型.只需将声明移到现有的类声明之外.
对于另一个警告,您需要创建一个PacketEventArgs
派生自EventArgs
并包含数据包数据的类作为额外属性.此时,您可以使用an EventHandler
而不是声明自己的委托.
另外:
您当前检查处理程序无效的方法已被破坏,因为它可能会在调用之间从非null变为null.
通常会调用事件PacketReceived
并且您的方法将被OnPacketReceived
(并受到保护),而不是相反.
有了这一切,你就拥有:
public event EventHandlerPacketReceived; protected virtual void OnPacketReceived(byte[] packet) { var handler = PacketReceived; if (handler != null) { handler.Invoke(this, new PacketEventArgs(packet)); } }
或者在C#6中,使用null条件运算符使实现更简单:
public event EventHandlerPacketReceived; protected virtual void OnPacketReceived(byte[] packet) { PacketReceived?.Invoke(this, new PacketEventArgs(packet)); }