Reputation: 21280
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
Upvotes: 10
Views: 31242
Reputation: 19294
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.
Upvotes: 1
Reputation: 16981
new Dictionary<Type, Func<object, int>>();
var cVisitor = new CVisitor();
_messageMapper.Add(typeof(Heartbeat),
new Func<object, int>(heartbeat => cVisitor.Visit((Heartbeat)heartbeat))
);
Upvotes: 9