Dictionary with delegate as meaning

I have the following class

public class CVisitor : IVisitor { public int Visit(Heartbeat element) { Trace.WriteLine("Heartbeat"); return 1; } public int Visit(Information element) { Trace.WriteLine("Information"); return 1; } } 

I want to have a dictionary with mappings that each type of argument will be mapped to its implementation function: Heartbeat will map to public int Visit(Heartbeat element)

I thought of doing something like the following:

  _messageMapper = new Dictionary<Type, "what should be here ?" >(); _messageMapper.Add(typeof(Heartbeat), "and how I put it here?" ); 

what should I put instead of "what should be here?" and "and how did I say that?"

thanks

+7
source share
3 answers
 new Dictionary<Type, Func<object, int>>(); var cVisitor = new CVisitor(); _messageMapper.Add(typeof(Heartbeat), new Func<object, int>(heartbeat => cVisitor.Visit((Heartbeat)heartbeat)) ); 
+7
source

Do you know Action and Func ? Looks like what you are looking for.

 var d = new Dictionary<Type, Action>(); d.Add(typeof(HeartBeat), ()=>Trace.WriteLine("todum todum")); 

PS: thanks YAG

+2
source

Your best challenge here is to use Reflection.
1. Get all the methods of the visitor class (or all the methods called "Visiting"?) Using typeof (Visitor) .GetMethods ().
2. GetMethods returns IEnumerable from MethodInfo. GetParameters will provide you with parameters for each method.
3. So, now you can create your Dictionnary of (Type, MethodInfo)
4. Use Invoke to call the method.

Rq: The advantage of using reflection is that Dictionnary will still be updated if you add a new method. There is no risk to forget about adding a method.

0
source

All Articles