Dictionary with delegate as value

I have 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 every argument type will be mapped to it's implementation function:Heartbeat will be mapped to public int Visit(Heartbeat element)

I thought to do something like following:

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

what should I put instead "what should be here ?" and "and how I put it here?"

Thanks

Answers


new Dictionary<Type, Func<object, int>>();

var cVisitor = new CVisitor();
_messageMapper.Add(typeof(Heartbeat), 
   new Func<object, int>(heartbeat => cVisitor.Visit((Heartbeat)heartbeat)) 
);

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

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

PS: thx YAG


Your best call here is to use Reflection. 1. Get all methods of Visitor Class (Or all methods called "Visit" ?) with typeof(Visitor).GetMethods(). 2. GetMethods returns an IEnumerable of MethodInfo. GetParameters will give you the parameters for each Method. 3. So now you can build your Dictionnary of (Type, MethodInfo) 4. use Invoke to call the Method.

Rq : An advantage of using reflection is that the Dictionnary will still be up to date if you add a new method. No risk of forgetting to add a method.


Need Your Help

Powershell Add_Click code only write-host working

forms powershell

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")

Reinitialise jQuery booklet plugin after page load

jquery plugins initialization options

Ref: jQuery booklet - http://builtbywill.com/code/booklet/options