我在向接口转换泛型时遇到问题,这个泛型实现
public interface IQuery<out TResult>
{
}
public interface IQueryRunner<in TQuery, out TResult> where TQuery : IQuery<TResult>
{
TResult Execute(TQuery query);
}
public interface IQueryRunnerFactory
{
IQueryRunner<IQuery<TResult>, TResult> CreateHandler<TResult>(IQuery<TResult> query);
}
public class QueryRunnerFactory : IQueryRunnerFactory
{
private readonly IServiceProvider dependencyResolver;
public QueryRunnerFactory(IServiceProvider dependencyResolver)
{
this.dependencyResolver = dependencyResolver;
}
public IQueryRunner<IQuery<TResult>, TResult> CreateHandler<TResult>(IQuery<TResult> query)
{
var genericType = typeof(IQueryRunner<,>).MakeGenericType(query.GetType(), typeof(TResult));
return this.dependencyResolver.GetService(genericType) as IQueryRunner<IQuery<TResult>, TResult>;
}
}
问题出在最后一行。 this.dependencyResolver.GetService(genericType)按预期返回一个处理程序。但是转换为接口返回null。如果我通过()运算符显式地转换它,它会抛出InvalidCastException。 AFAIU的问题在于IQuery < TResult >
泛型参数。是不是协变的,所以它不能被铸造。但我不能在这里使用out
关键字,因为它不允许在泛型方法中使用。我该如何解决这个问题?