Question

static Dictionary<Type, Action<object>> handlers;

public static void Main (string[] args)
{
    handlers = new Dictionary<Type, Action<object>>();

    AddHandler<One>((object rawOne) => { One one = (One)rawOne; Console.WriteLine(one.Data); });
    AddHandler<Two>((object rawTwo) => { Two two = (Two)rawTwo; Console.WriteLine(two.Data); });

    Handle(new One("Test"));
    Handle(new Two(123));
}

public static void AddHandler<T>(Action<object> handler)
{
    handlers[typeof(T)] = handler;
}

public static void Handle(object data)
{
    handlers[data.GetType()].Invoke(data);
}

For lack of a better way to word this: How would I go about making this in a way where I would not have to cast rawOne and rawTwo?

Basically, I want this:

AddHandler<One>((object rawOne) => { One one = (One)rawOne; 
Console.WriteLine(one.Data); });

To look like this:

AddHandler<One>((One one) => { Console.WriteLine(one.Data); };

But, I'm not sure how to accomplish this. Obviously I've got to modify the dictionary in some way, but I have no idea how.

Was it helpful?

Solution

Like this:

public static void AddHandler<T>(Action<T> handler)
{
    handlers[typeof(T)] = o => handler((T)o);
}

Furthermore, since the compiler can infer certain things about your types, you could say either this:

AddHandler((One one) => { Console.WriteLine(one.Data); };

... or this:

AddHandler<One>(one => { Console.WriteLine(one.Data); };
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top