خرید بک لینک

Vote count: 0

(I really tried to come up with a better title, feel free to edit)

Suppose I have a generic event handler interface and implementations:

public interface IEventHandler<T>
{
    void HandleEvent(T t);
}

public class SlowButAccurateEventHandler<T> : IEventHandler<T>
{
    void HandleEvent(T t) { ... }
}

public class FastEventHandler<T> : IEventHandler<T>
{
    void HandleEvent(T t) { ... }
} 

and another class which I'd like to hold instances of EventHandlers, but caot have generic methods since it's a WCF service:

public class MyService : MyContract
{
    // Pseudo (doesn't compile)
    private Dictionary<Type, IEventHandler<T>> eventHandlers;

    public MyService()
    {
        // More pseudo...
        eventHandlers = new Dictionary<Type, IEventHandler<T>>()
        {  
            { typeof(string), new SlowButAccurateEventHandler<string>() },
            { typeof(int), new FastEventHandler<int>() },
        };    
    }
    public void RouteToEventHandler(object userEvent)
    {
       var handler = eventHandlers[typeof(userEvent))];
       handler.HandleEvent(userEvent); // I realize that userEvent needs to be converted here
    }
}

So basically, I have some service (MyService) that I'd like to hold IEventHandlers and dispatch the correct handler when some event arrives. To do that, I'd like to keep a dictionary that holds a mapping between the CLR type and the suitable IEventHandler. Is that possible?

asked 1 min ago

برچسب: نویسنده: استخدام کار تاريخ: يکشنبه 19 ارديبهشت 1395 ساعت: 23:03

صفحه بندی