Shervin Ivari
Shervin Ivari

Reputation: 2501

Assign event and function in extension method as argument

I have a list of objects and I want to assign values in a factory method. I have checked similar questions but they have access to a method in existing assembly. I want to use a custom method and also define which event should be set.

for example

mylist.Assign(nameofevent,assignfuntion);

the usage something like

public static void Assign(this Control[] controls,eventhandler @event,Action func)
{
  foreach (var item in controls)
  //assign function to event
    item.clicked += func;//Preferably clicked must be Specified from argument
}

Upvotes: 0

Views: 112

Answers (1)

Davey van Tilburg
Davey van Tilburg

Reputation: 718

Trying to help to get to the bottom of what is wrong with Shervin Ivari's question. I'm illustration how you can achieve it. But still unsure if this is what you want?

public static void Main()
{
    var listeners = new List<SomeClassWithListener>
    {
        new SomeClassWithListener(),
        new SomeClassWithListener(),
        new SomeClassWithListener()
    };

    var theEvent = new SomeClassWithEvent();

    MatchEmUp(listeners, theEvent);

    theEvent.RaiseEvent();
}

public static void MatchEmUp(IEnumerable<SomeClassWithListener> listeners, SomeClassWithEvent theEvent)
{
    foreach(SomeClassWithListener listener in listeners)
        theEvent.ItsAlive += listener.ThenIllSlayIt;
}

public class SomeClassWithListener
{
    public void ThenIllSlayIt(object sender, EventArgs e)
    {
        Console.WriteLine("Chaaaaaarge!");
    }
}

public class SomeClassWithEvent
{
    public EventHandler ItsAlive;

    public void RaiseEvent()
    {
        ItsAlive.Invoke(this, new EventArgs());
    }
}

https://dotnetfiddle.net/4Y13cf

Or by using delegates, EventHandler is also a delegate:

public static void Main()
{
    var listener1 = new SomeClassWithListener();
    var listener2 = new SomeClassWithListener();
    var listener3 = new SomeClassWithListener();

    var listeners = new List<EventHandler>
    {
        listener1.ThenIllSlayIt,
        listener2.ThenIllSlayIt,
        listener3.ThenIllSlayIt
    };

    var theEvent = new SomeClassWithEvent();

    MatchEmUp(listeners, theEvent);

    theEvent.RaiseEvent();
}

public static void MatchEmUp(IEnumerable<EventHandler> listeners, SomeClassWithEvent theEvent)
{
    foreach(EventHandler listener in listeners)
        theEvent.ItsAlive += listener;
}

public class SomeClassWithListener
{
    public void ThenIllSlayIt(object sender, EventArgs e)
    {
        Console.WriteLine("Chaaaaaarge!");
    }
}

public class SomeClassWithEvent
{
    public EventHandler ItsAlive;

    public void RaiseEvent()
    {
        ItsAlive.Invoke(this, new EventArgs());
    }
}

https://dotnetfiddle.net/k16lsy

Upvotes: 1

Related Questions