简体   繁体   English

如何将匿名事件处理程序重构为适当的“委托”?

[英]How to refactor an anonymous event handler to a proper "delegate?"

Ok so I am aware there are some similar questions such as:好的,所以我知道有一些类似的问题,例如:

Adding and Removing Anonymous Event Handler Unsubscribe anonymous method in C# 在 C# 中添加和删除匿名事件处理程序取消订阅匿名方法

But I don't understand the concept of delegates.但是我不明白代表的概念。

I am starting to use the Plugin.BLE in a.Net Maui app.我开始在 a.Net Maui 应用程序中使用 Plugin.BLE。

The scanning operation is started from a button and then either times out (by use of a Timer) or is stopped by pressing the button again.扫描操作从一个按钮开始,然后超时(通过使用计时器)或通过再次按下按钮停止。

However in my button command (MVVM) I have the following snippet of code:但是在我的按钮命令(MVVM)中,我有以下代码片段:

      ...
      adapter.DeviceDiscovered += (s, a) =>
      {
        if (a.Device.Name != null && a.Device.Name != String.Empty)
        {
          ...
        }
      };

      await adapter.StartScanningForDevicesAsync();
      ...

I note that each time I hit the button I get two more discovered items (I'm not sure why I'm getting 2 yet?) (This is from Pixel 5 emulator)我注意到每次我按下按钮时,我都会得到两个发现的项目(我不确定为什么我会得到 2 个?)(这是来自 Pixel 5 模拟器)

This makes some kind of sense as I am adding another event to the same adapter这有点道理,因为我正在向同一个适配器添加另一个事件

So I need to convert the anonymous function所以我需要转换匿名 function

 adapter.DeviceDiscovered += (s, a) =>
 {
 }

into a non anonymous function, so that I can add the handler and then remove it when the timer stops or I stop the function.进入非匿名 function,这样我就可以添加处理程序,然后在计时器停止或停止 function 时将其删除。

I have no idea how to go about this, especially in dealing with the s and the a.我不知道如何 go 关于这个,特别是在处理 s 和 a 时。

I'd be grateful for any pointers, code.我将不胜感激任何指针,代码。

Thanks, G.谢谢,G。

Edit: link to Plguin.BLE https://github.com/xabre/xamarin-bluetooth-le编辑:链接到 Plguin.BLE https://github.com/xabre/xamarin-bluetooth-le

Well, I am truly astonished by Visual Studio.好吧,我真的对 Visual Studio 感到惊讶。

After hacking away for a while trying to create functions and delegates I commented out the code and typed in在尝试创建函数和委托一段时间后,我注释掉了代码并输入了

adapter.DeviceDiscovered +=

and visual studio created the rest of the code and the event handler for me. Visual Studio 为我创建了代码的 rest 和事件处理程序。

So I have:所以我有:

adapter.DeviceDiscovered += Adapter_DeviceDiscovered;

...

private void Adapter_DeviceDiscovered(object s, Plugin.BLE.Abstractions.EventArgs.DeviceEventArgs a)
{
  Debug.WriteLine("Got here");
}

I changed the original sender to s and the original e to a to match the code I was using.我将原始发件人更改为 s 并将原始 e 更改为 a 以匹配我使用的代码。

Well so far it seems to work.到目前为止,它似乎有效。

Now all I need to do is figure out why this is getting called twice:.sigh: )现在我需要做的就是弄清楚为什么这会被调用两次:.sigh:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM