See Enigmativity's answer for a much clearer phrasing of this question.
I have a generic Action
that I am registering for, and then casting to the type I am expecting:
public interface IMyInterface { }
public static Action<IMyInterface> MyAction;
public class MyClass : IMyInterface { }
public void Subscribe()
{
MyAction<MyClass> += MyMethod;
}
public void MyMethod(IMyInterface myInterface)
{
var myClass = (MyClass)myInterface;
}
But I want to be able to subscribe with a method that already dictates the type so I can avoid the extra step of casting. Is it possible to only subscribe to MyActions such that IMyInterface has a specific type? So that MyMethod
can be like this:
public void MyMethod(MyClass myClass)
{
}
The reason I am trying to do this is because I am writing a messaging system which uses the specific type. I am using generics to determine which messages to subscribe to. I don't think this part affects my question, but here is what that looks like:
private Dictionary<Type, List<Action<IMessage>> subscribers = new Dictionary<Type, List<Action<IMessage>>();
public void SubscribeMessage<TMessage>(Action<IMessage> callback)
where TMessage : IMessage
{
var type = typeof(TMessage);
if (subscribers.ContainsKey(type))
{
if (!subscribers[type].Contains(callback))
{
subscribers[type].Add(callback);
}
else
{
LogManager.LogError($"Failed to subscribe to {type} with {callback}, because it is already subscribed!");
}
}
else
{
subscribers.Add(type, new List<Action<IMessage>>());
subscribers[type].Add(callback);
}
}
public void UnsubscribeMessage<TMessage>(Action<IMessage> callback)
where TMessage : IMessage
{
var type = typeof(TMessage);
if (subscribers.ContainsKey(type))
{
if (subscribers[type].Contains(callback))
{
subscribers[type].Remove(callback);
}
else
{
LogManager.LogError($"Failed to unsubscribe from {type} with {callback}, because there is no subscription of that type ({type})!");
}
}
else
{
LogManager.LogError($"Failed to unsubscribe from {type} with {callback}, because there is no subscription of that type ({type})!");
}
}
//The use case given MyClass implements IMessage
public void Subscribe()
{
SubscribeMessage<MyClass>(MyMethod);
}
public void MyMethod(IMessage myMessage)
{
var myClass = (MyClass)myMessage;
}
So is it possible for me to subscribe to a generic Action
with a method that has a concrete type?