In .NET applications, normally events are wired this way:
public event EventHandler<ChangeEventArgs> OnChange
{
add { _dependency.OnChange += value; }
remove { _dependency.OnChange -= value; }
}
However this only works if the events being wired have the same event handler. In my current case, the original event args is proprietary of a library, and I don't want to expose that to the client code. So I have some kind of adapter (ChangeEventArgs). How can I use the code above to convert the event args? I imagine something like below (but below code doesn't work)
public event EventHandler<ChangeEventArgs> OnChange
{
add { _dependency.OnChange += Convert(value); }
remove { _dependency.OnChange -= Convert(value); }
}
or
public event EventHandler<ChangeEventArgs> OnChange
{
add { _dependency.OnChange += value(this, Convert(args)); }
remove { _dependency.OnChange -= value(this, Convert(args)); }
}
Try this:
public class SomeClassAdapter
{
private readonly SomeClass obj;
public SomeClassAdapter(SomeClass obj)
{
this.obj = obj;
this.obj.SomeEvent += HandleSomeClassSomeEvent;
}
private void HandleSomeClassSomeEvent(object sender, SomeEventArgs args)
{
OnSomeEvent(ConvertEventArgs(args));
}
private MyEventArgs ConvertEventArgs(SomeEventArgs args)
{
// the magic goes here...
}
protected virtual void OnSomeEvent(MyEventArgs args)
{
var handler = SomeEvent;
if (handler != null)
{
handler(this, args);
}
}
public event EventHandler<MyEventArgs> SomeEvent;
}
Update.
This code uses more complex version of adapter pattern, than your code does. SomeClassAdapter
is an adapter for SomeClass
(it has SomeClass
instance in its private field obj
).
Client code subscribes to my SomeClassAdapter.SomeEvent
. My code, in turn, subscribes to SomeClass.SomeEvent
. When SomeClass.SomeEvent
is fired, my event handler (HandleSomeClassSomeEvent
) is called. This event handler converts SomeEventArgs
to MyEventArgs
and raises SomeClassAdapter.SomeEvent
.
So, we have the chain: SomeClass.SomeEvent
-> HandleSomeClassSomeEvent
-> SomeClassAdapter.SomeEvent
. Looks like "event proxy".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With