我正在建造一个简单的“公共汽车”作为概念证明。我不需要任何复杂的东西,但想知道如何最好地优化以下代码。我使用 Autofac 作为容器将命令解析为开放的泛型,但实际上执行命令当前是通过反射完成的,因为传入的命令无法转换为代码中的具体类型。请参阅代码 - 用 // BEGIN // END 标记 - 目前正在通过反射完成。有没有办法在不使用反射的情况下做到这一点?
// IoC wrapper
static class IoC {
public static object Resolve(Type t) {
// container gubbins - not relevant to rest of code.
}
}
// Handler interface
interface IHandles<T> {
void Handle(T command);
}
// Command interface
interface ICommand {
}
// Bus interface
interface IBus {
void Publish(ICommand cmd);
}
// Handler implementation
class ConcreteHandlerImpl : IHandles<HelloCommand> {
public void Handle(HelloCommand cmd) {
Console.WriteLine("Hello Command executed");
}
}
// Bus implementation
class BusImpl : IBus {
public void Publish(ICommand cmd) {
var cmdType = cmd.GetType();
var handler = IoC.Resolve(typeof(IHandles<>).MakeGenericType(cmdType));
// BEGIN SLOW
var method = handler.GetType().GetMethod("Handle", new [] { cmdType });
method.Invoke(handler, new[] { cmd });
// END SLOW
}
}