我正在構建一個簡單的「公共汽車」作爲概念證明。我不需要任何複雜的東西,但是想知道如何優化下面的代碼。我使用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'類型了......不需要動態地生成泛型... –