将通用类型转换为基类型

时间:2017-07-18 14:33:06

标签: c# generics

我有下一个场景:

public class RequestBase { }
public class ResponseBase { }

public interface IService<TRequest, TResponse>
           where TRequest : RequestBase where TResponse : ResponseBase
{
    TResponse Execute(TRequest request);
}

public class MyRequest : RequestBase { }
public class MyResponse : ResponseBase { }

public class MyService : IService<MyRequest, MyResponse>
{
    public MyResponse Execute(MyRequest request)
    {
        return new MyResponse();
    }
}

现在我正在创建将创建我的服务的工厂:

class ServicesFactory
{
    public IService<RequestBase, ResponseBase> Create()
    {
        var service = new MyService();
        return (IService<RequestBase, ResponseBase>)service;
    }    
}

问题在于投掷抛出异常。

如何将派生类型转换为基类型?

1 个答案:

答案 0 :(得分:3)

使您的界面在TResponse上协变:

public interface IService<TRequest, out TResponse>

您就可以将MyService转换为IService<MyRequest, ResponseBase>。请注意,无法转换为IService<RequestBase, ResponseBase>,因为并非所有RequestBase都是MyRequest

也就是说,您可以使用不同的类来装饰MyService,该类将在运行时检查RequestBase中是否传递了MyRequest。当然,如果接口需要任何RequestBase,那么这会违反LSP。