I want to create a fluent extension method for subscribing to (and less importantly unsubscribing from) an event. That is an extension with the usage .RespondBy(Method)
in place of a += new Eventhandler(Method)
I want to do this: object.WhenSomethingChanges.RespondBy(DoingThisOtherThing);
Instead of this: object.WhenSomethingChanges += new EventHandler(DoingThisOtherThing);
I did a bunch of googling and while I didn't exactly grasp the intricate details, I do understand now that this has to do with whether you are accessing the local field or the public event.
With that said, I am simply interested in "how" this can be done and not concerned with "why" my first attempt hasn't worked. Failing a workaround, at least a definitive "You can not do this... at all, ever." would also be useful information...
CommuncationsStatusPresenter (Image)
CommuncationsStatusPresenter (Code)
using System;
using InspectionStation.Models;
using InspectionStation.Views;
using MachineControl.OPC;
namespace InspectionStation.Presenters
{
public class CommuncationsStatusPresenter
{
// Fields
private ICommunicationsModel m_model;
private ICommunicationsView m_view;
// Constructor
public CommuncationsStatusPresenter
(ICommunicationsModel p_model, ICommunicationsView p_view)
{
m_model = p_model;
m_view = p_view;
HookEvents();
}
private void HookEvents()
{
m_model
.When_Communications_Pulses_Heartbeat
.RespondBy(Setting_the_state_of_an_Indicator);
}
// Eventhandler
void Setting_the_state_of_an_Indicator(Tag sender, EventArgs e)
{
bool State = sender.BooleanValue;
m_view.Set_Communications_Status_Indicator = State;
}
}
}
RespondBy
using System;
namespace Common.Extensions
{
public static partial class ExtensionMethods
{
public static
void RespondBy<TSender, TEventArgs>(this
GenericEventHandler<TSender, TEventArgs> p_event,
GenericEventHandler<TSender, TEventArgs> p_handler
) where TEventArgs : EventArgs
{
p_event += new GenericEventHandler<TSender, TEventArgs>(p_handler);
}
}
}
using System;
namespace Common
{
[SerializableAttribute]
public delegate void GenericEventHandler<TSender, TEventArgs>
(TSender sender, TEventArgs e)
where TEventArgs : EventArgs;
}
ICommunicationsModel
using System;
using Common;
using MachineControl.OPC;
namespace InspectionStation.Models
{
public interface ICommunicationsModel
{
event GenericEventHandler<Tag, EventArgs>
When_Communications_Pulses_Heartbeat;
}
}
ICommunicationsView
namespace InspectionStation.Views
{
public interface ICommunicationsView
{
bool Set_Communications_Status_Indicator { set; }
}
}