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
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 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)
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.
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.
new Dictionary<Type, Func<object, int>>();
var cVisitor = new CVisitor();
_messageMapper.Add(typeof(Heartbeat),
new Func<object, int>(heartbeat => cVisitor.Visit((Heartbeat)heartbeat))
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With