I'm trying to hold in memory a collection of references of type Action<T>
where T is variable type
I've found a solution with dynamic
but I would prefer not to use dynamic the solution
public class MessageSubscriptor:IMessageSubscriptorPool
{
Dictionary<Type, Action<dynamic>> Callbacks = new Dictionary<Type, Action<dynamic>>();
public void Subscribe<T>(Action<T> callback) where T :IMessage
{
Callbacks.Add(typeof(T), (obj) => callback(obj));
}
}
Does anyone know a better approach to handling this? Thanks in advance.
Action<T> Delegate (System)Encapsulates a method that has a single parameter and does not return a value.
Action is a delegate type defined in the System namespace. An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type. For example, the following delegate prints an int value.
Func is a delegate that points to a method that accepts one or more arguments and returns a value. Action is a delegate that points to a method which in turn accepts one or more arguments but returns no value. In other words, you should use Action when your delegate points to a method that returns void.
Action<T>
is a Delegate
, therefore...
public class MessageSubscriptor:IMessageSubscriptorPool
{
private readonly Dictionary<Type, Delegate> _callbacks = new Dictionary<Type, Delegate>();
public void Subscribe<T>(Action<T> callback) where T :IMessage
{
_callbacks.Add(typeof(T), callback);
}
}
Then, say you want to invoke one, you can simply perform a cast:
public void Invoke<T>(T message) where T :IMessage
{
Delegate callback;
if (_callbacks.TryGetValue(typeof(T), out callback))
((Action<T>)callback).Invoke(message);
}
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