简体   繁体   中英

Pass extra parameters to an event handler?

Let's say I want to pass some extra data when assigning an event handler. Consider the following code:

private void setup(string someData)
{
     Object.assignHandler(evHandler);
}

public void evHandler(Object sender)
{
    // need someData here!!!
}

How would I go about getting someData into my evHandler method?

private void setup(string someData)
{
     Object.assignHandler((sender) => evHandler(sender,someData));
}
public void evHandler(Object sender, string someData)
{
    // need someData here!!!
}

I had a hard time figuring out @spender's example above especially with: Object.assignHandler((sender) => evHandler(sender,someData)); because there's no such thing as Object.assignHandler in the literal sense. So I did a little more Googling and found this example . The answer by Peter Duniho was the one that clicked in my head (this is not my work):

snip

The usual approach is to use an anonymous method with an event handler that has your modified signature. For example:

 void Onbutton_click(object sender, EventArgs e, int i) { ... } button.Click += delegate(object sender, EventArgs e) { Onbutton_click(sender, e, 172); };

Of course, you don't have to pass in 172, or even make the third parameter an int. :)

/snip

Using that example I was able to pass in two custom ComboBoxItem objects to a Timer.Elapsed event using lambda notation:

simulatorTimer.Elapsed +=
(sender, e) => onTimedEvent(sender, e,
(ComboBoxItem) cbPressureSetting.SelectedItem,
(ComboBoxItem) cbTemperatureSetting.SelectedItem);

and then into it's handler:

static void onTimedEvent(object sender, EventArgs e, ComboBoxItem pressure, ComboBoxItem temperature)
    {
        Console.WriteLine("Requested pressure: {0} PSIA\nRequested temperature: {1}° C", pressure, temperature);
    }

This isn't any new code from the examples above, but it does demonstrate how to interpret them. Hopefully someone like me finds it instructive & useful so they don't spend hours trying to understand the concept like I did.

This code works in my project (except for a non-thread-safe exception with the ComboBoxItem objects that I don't believe changes how the example works). I'm figuring that out now.

Captured variables:

private void setup(string someData)
{
    Object.assignHandler((sender,args) => {
        evHandler(sender, someData);
    });
}

public void evHandler(Object sender, string someData)
{
    // use someData here
}

Or (C# 2.0 alternative):

    Object.assignHandler((EventHandler)delegate(object sender,EventArgs args) {
        evHandler(sender, someData);
    });

you can try doing this:

string yourObject;

theClassWithTheEvent.myEvent += (sender, model) =>
{
 yourObject = "somthing";
}

My question that was similar was marked a duplicate so thought I'd add an answer here since it won't let me on my question.

class Program
    {
        delegate void ComponentEventHandler(params dynamic[] args);

        event ComponentEventHandler onTest;

        static void Main(string[] args)
        {  
            Program prg = new Program();

            // can be bound to event and called that way
            prg.onTest += prg.Test;
            prg.onTest.Invoke("What", 5, 12.0);

            Console.ReadKey();
        }

        public void Test(params dynamic[] values)
        {
            // assign our params to variables
            string name = values[0];
            int age = values[1];
            double value = values[2];

            Console.WriteLine(name);
            Console.WriteLine(age);
            Console.WriteLine(value);
        }
    }

You could create a custom object having additional properties based on Object:

class CustomObject : Object
{
    public string SomeData;
}

private void setup(string someData)
{
    CustomObject customObject = new CustomObject { SomeData = someData };
    CustomObject.assignHandler(evHandler);
}

public void evHandler(Object sender)
{
    string someData = ((CustomObject)sender).SomeData;
}

If the data should not be changed anymore after initialization, you could also add a custom constructor, for example.

Here is my one-line solution that pass extra parameters to a timer handler.

private void OnFailed(uint errorCode, string message)
{
    ThreadPoolTimer.CreateTimer((timer) => {
    UI.ErrorMessage = string.Format("Error: 0x{0:X} {1}", errorCode, message);
    }, System.TimeSpan.FromMilliseconds(100));
}

Well, the simplest method id to make someData a member variable like so:

public class MyClass
{
    private string _eventData;

    private void setup(string someData) 
    {
       _eventData = someData;
       Object.assignHandler(evHandler);
    }

    public void evHandler()
    {
        // do something with _eventData here
    }
}

I'm not sure that's the best way to do it, but it really depends on the event type, the object, etc.

My solution involves subscribing to my event with an action that invokes a lambda function that supplies my event handler with the event args and my extra parameter. I then store this action in a dictionary. When I want to unsubscribe, I can use the stored actions to do so.

This works, I read the length of listeners before and after unsubscribing and it did decrease.

    public class Player
    {
        public Action<JumpInfo> OnJump;
    }

    public class PlayerJumpListener
    {
        public List<Player> MyPlayerList;
        private Dictionary<Player, Action<JumpInfo>> _jumpActionsByPlayer = new Dictionary<Player, Action<JumpInfo>>();

        private void Subscribe()
        {
            foreach (Player player in MyPlayerList)
            {
                Action<JumpInfo> playerJumpAction = (jumpInfo) => HandlePlayerJump(jumpInfo, player);
                player.OnJump += playerJumpAction;

                _jumpActionsByPlayer.Add(player, playerJumpAction);
            }
        }

        private void Unsubscibe()
        {
            foreach (KeyValuePair<Player, Action<JumpInfo>> kvp in _jumpActionsByPlayer)
            {
                kvp.Key.OnJump -= kvp.Value;
            }
        }

        private void HandlePlayerJump(JumpInfo jumpInfo, Player player)
        {
            // player jumped
        }
    }

I scoured the internet before a coworker kindly helped me, and boy I felt dumb. Brackets is the solution for the EventHandler .

Ex.

event EventHandler<(int, bool)> EventName;

and then pick it up with:

private void Delegate_EventName(object sender, (int, bool) e)

you can then access the info:

var temp = e.Item1;<br>
var temp2 = e.Item2;<br>

or you can add names as you would expect for parameters and call them via e :

private void Delegate_EventName(object sender, (int num, bool val) e)

you can then access the info:

var temp = e.num;
var temp2 = e.val;

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