我正在构建一个简单的“公共汽车”作为概念证明。我不需要任何复杂的东西,但是想知道如何优化下面的代码。我使用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
}
}
现在添加通用约束并进行测试 - 感谢回复。将成功发布(希望)。 – Deleted
非常好 - 非常感谢。完美的作品!我可以看到约束如何在不破坏运行时或编译器的情况下强制类型被强制。好的解决方案再次感谢。 – Deleted
嗯......我在这里错过了什么吗?为什么不只是'var handler = IoC.Resolve>();'?你已经知道'T'类型了......不需要动态地生成泛型... –