我必须从另一个类中的事件访问数据。 在那个课程中,事情是这样的:
namespace MavLink
{
public class Mavlink
{
...
public event PacketReceivedEventHandler PacketReceived;
...
private void ProcessPacketBytes(byte[] packetBytes, byte rxPacketSequence)
{
...
if (PacketReceived != null)
{
PacketReceived(this, packet);
}
...
}
}
public delegate void PacketReceivedEventHandler(object sender, MavlinkPacket e);
}
在主要方面,我试图这样做:
...
m.ParseBytes(newlyReceived);
m.PacketReceived += (sender, e) => {
Console.WriteLine(e.SystemId);
Console.WriteLine(e.ComponentId);
Console.WriteLine(e.SequenceNumber);
Console.WriteLine(e.TimeStamp);
Console.WriteLine(e.Message);
};
但它似乎不起作用。
感谢您的帮助。
编辑: 它编译时没有错误,但控制台上没有打印任何内容。我不知道如何检查事件是否已经上升。
答案 0 :(得分:0)
我做了一个例子,工作正常,希望它有所帮助。用PacketRecievedEventHandler替换EventHandler:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var sender = new Sender();
var reciever = new Reciever(sender);
sender.ProcessPacketBytes(null, byte.MaxValue);
Console.ReadLine();
}
}
/// <summary></summary>
public class Sender
{
private readonly object _objectLock = new object();
public event EventHandler PacketReceived
{
add
{
lock (_objectLock)
{
PacketRecievedEvent += value;
}
}
remove
{
lock (_objectLock)
{
PacketRecievedEvent -= value;
}
}
}
private event EventHandler PacketRecievedEvent;
public void ProcessPacketBytes(byte[] packetBytes, byte rxPacketSequence)
{
EventHandler handler = this.PacketRecievedEvent;
if (handler != null)
{
handler(this, new EventArgs());
}
}
}
public class Reciever
{
public Reciever(Sender sendertest)
{
sendertest.PacketReceived += (sender, e) =>
{ Console.WriteLine(e.GetType()); };
}
}
}
答案 1 :(得分:0)
在我看到的内容中,我创建了一个通常的事件,可以为您提供一些数据。
我们从创建活动开始。
public delegate void PacketReceivedEventHandler(var pPacket);
public event PacketReceivedEventHandler PacketReceived;
我把var放在那里因为我没有完全看到你是什么&#34;交付&#34;。只需将其更改为您需要的任何内容。
所以,让我们继续。当需要触发事件时放置它。
if (Mavlink.PacketReceived != null)
Mavlink.PacketReceived(YourPackage);
YourPackage 是您想要提供的任何内容。
但是你需要订阅一个事件来做它的事情。
Mavlink.PacketReceived += Mavlink_PacketReceived;
如果你在+ =后加倍制表,C#通常会创建一个类。但这是我创建的课程。
private void Mavlink_PacketReceived(var pPacket)
{
if(pPacket != null)
{
Console.WriteLine(pPacket.SystemId);
Console.WriteLine(pPacket.ComponentId);
Console.WriteLine(pPacket.SequenceNumber);
Console.WriteLine(pPacket.TimeStamp);
Console.WriteLine(pPacket.Message);
}
}
我不知道你的代码后面会发生什么,但要确保有一些东西可以使命令行等待,所以它在解雇后不会关闭。