我有以下类(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;
        }

    }

我想要一个带有映射的Dictionary,每个参数类型都将映射到它的实现函数:Heartbeat将映射到public int Visit(Heartbeat element)
我想做些类似的事情:
    _messageMapper = new Dictionary<Type, "what should be here ?" >();
    _messageMapper.Add(typeof(Heartbeat), "and how I put it here?" );

我应该改写什么:“这里应该是什么?”和“以及我如何将其放置在这里?”

谢谢

最佳答案

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

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

10-06 11:30