我的通用方法就是这个
public static class AppContainerInstaller
{
public static IMessageHandler<T> Resolve<T>()
{
return _container.Resolve<IMessageHandler<T>>();
}
}
我试图从另一个类
调用这个泛型方法public static string ProcessMessage(IMessage message)
{
messageHandler = AppContainerInstaller.Resolve<message.GetType()>();
// THe previous line throws an error.
return messageHandler.Handle(message);
}
有谁能告诉我如何将消息类型传递给泛型方法?
答案 0 :(得分:5)
你必须这样做:
messageHandler = AppContainerInstaller.Resolve<IMessage>();
Resolve
方法是应该在T中传递类型的方法。您可以看到,在使用泛型时,您必须提供实际类型。您可能希望更改Resolve
以获得T参数,因此您可以传递message
。像这样:
public static IMessageHandler<T> Resolve<T>(T param)
你这样称呼它:
messageHandler = AppContainerInstaller.Resolve<IMessage>(message);
答案 1 :(得分:1)
获取运行时类型有两种方法:将消息作为参数传递或使用反射。
修改方法:
public static IMessageHandler<T> Resolve<T>(T unused)
{
return _container.Resolve<IMessageHandler<T>>();
}
允许运行时类型查找:
// Cast to dynamic to force runtime type
messageHandler = AppContainerInstaller.Resolve((dynamic) message);
虽然存在性能损失,但您也可以使用反射。
private static readonly MethodInfo ResolveMethodInfo
= typeof(AppContainerInstaller).GetMethod("Resolve", BindingFlags.Public | BindingFlags.Static);
// Assuming there exists a non-generic interface IMessageHandler
private readonly ConcurrentDictionary<Type, Func<IMessageHandler>> _methodCache
= new ConcurrentDictionary<Type, Func<IMessageHandler>>();
public static string ProcessMessage(IMessage message)
{
messageHandler = Resolve(message.GetType());
return messageHandler.Handle(message);
}
private IMessageHandler Resolve(Type type)
{
// Cache the generated method to avoid repeated reflection penalty.
var resolve = _methodCache.GetOrAdd(type, () => ResolveMethodInfo.MakeGenericMethod(type));
return resolve();
}