Reputation: 7246
I created the below event in my MessageDeserializer
class, which uses interface IDeserializer<DpdMessage>
:
public event Action<int> OnUnsupportedMessage;
When I'm now trying to subscribe to the event in my Health class by injecting IDeserializer<DpdMessage>
into the constructor as follows:
public Health(IDeserializer<DpdMessage> msg)
{
_msg = msg;
_msg.OnUnsupportedMessage += OnMessage;
}
I get this error:
Error CS1061 'IDeserializer' does not contain a definition for 'OnUnsupportedMessage' and no accessible extension method 'OUnsupportedMessage' accepting a first argument of type 'IDeserializer' could be found (are you missing a using directive or an assembly reference?)
I can't simply add the event to the interface as it's in an external package.
How do I subscribe to my event?
Upvotes: 1
Views: 57
Reputation: 840
You could extend the interface by declaring your own interface that adds the event functionality you need. If you did something similar to the code below, you could then inject this interface instead of the one from the external package.
public interface IDeserializerWrapper<T>: IDeserializer<T>
{
event Action<int> OnUnsupportedMessage;
}
public class MessageDeserializer: IDeserializerWrapper<MdpMessage>
{
public event Action<int> OnUnsupportedMessage;
//...rest of interface methods
}
class Health
{
private IDeserializerWrapper<MdpMessage> _msg;
public Health(IDeserializerWrapper<MdpMessage> msg)
{
_msg = msg;
_msg.OnUnsupportedMessage += OnMessage;
}
public void OnMessage(int n)
{
//...whatever this method does
}
}
Upvotes: 0
Reputation: 4002
You have define OnUnsupportedMessage
in your MessageDeserializer
, so only instances of this class (or subclasses of it) will have this event.
If you have no control over IDeserializer<DpdMessage>
interface, you may try casting it to your class like this:
if (msg is MessageDeserializer m)
m.OnUnsupportedMessage += OnMessage;
Upvotes: 1