简体   繁体   中英

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#

But I don't understand the concept of delegates.

I am starting to use the Plugin.BLE in a.Net Maui app.

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:

      ...
      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)

This makes some kind of sense as I am adding another event to the same adapter

So I need to convert the anonymous 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.

I have no idea how to go about this, especially in dealing with the s and the a.

I'd be grateful for any pointers, code.

Thanks, G.

Edit: link to Plguin.BLE https://github.com/xabre/xamarin-bluetooth-le

Well, I am truly astonished by 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.

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.

Well so far it seems to work.

Now all I need to do is figure out why this is getting called twice:.sigh: )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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