Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Action<T> in a single collection for later usage

Tags:

c#

generics

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.

like image 601
borja gómez Avatar asked Aug 31 '15 08:08

borja gómez


People also ask

What is action t used for in an application?

Action<T> Delegate (System)Encapsulates a method that has a single parameter and does not return a value.

What Is an Action delegate?

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.

What is the delegate type called when a value is returned instead of an action performed?

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.


1 Answers

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);
}
like image 95
Lucas Trzesniewski Avatar answered Sep 23 '22 14:09

Lucas Trzesniewski