Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary with delegate as value

Tags:

c#

.net

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

like image 510
Night Walker Avatar asked Jul 16 '12 12:07

Night Walker


People also ask

What is the difference between key and value of a delegate?

Dictionary’s key and value are generic types. In this way delegates can be set as key or value. What is Delegate? “A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++.

What is a delegate?

What is Delegate? “A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered.” ( more info)

Is there a new dictionary<type> with delegate() option?

So new Dictionary<Type, Delegate> () is a possibility. But it does not ensure that the value delegate is related in any way to the dictionary key (the Type ). And like I said, I'm not sure this approach is useful.

How do you call a method from a delegate?

Using Delegates (C# Programming Guide) Once a delegate is instantiated, a method call made to the delegate will be passed by the delegate to that method. The parameters passed to the delegate by the caller are passed to the method, and the return value, if any, from the method is returned to the caller by the delegate.


1 Answers

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

var cVisitor = new CVisitor();
_messageMapper.Add(typeof(Heartbeat), 
   new Func<object, int>(heartbeat => cVisitor.Visit((Heartbeat)heartbeat)) 
);
like image 113
Serj-Tm Avatar answered Oct 09 '22 12:10

Serj-Tm