无法将类型 IResponse 隐式转换为 TResponse [重复]

问题描述 投票:0回答:1

我有一个类

Test
继承了
ITest<TRequest>

public interface ITest<TRequest>
{
    TResponse TestMethod <TResponse>(TRequest request) where TResponse : IResponse;
}
public class Test : ITest<Request>
{
    public TResponse TestMethod <TResponse>(Request request) where TResponse : IResponse
    {
        //Error CS0266  Cannot implicitly convert type 'IResponse' to 'TResponse'. An explicit conversion exists (are you missing a cast?)
        return this.TestMethod(request);
    }

    public IResponse TestMethod (Request request)
    {     
        IResponse response = new Response();     
        return response; 
    }
}

我的问题是为什么我需要在这里进行显式转换?

c#
1个回答
0
投票

TestMethod<TResponse>
是一个泛型方法,因此可以用任何符合其实现
IResponse
要求的类型来调用它。例如:

internal class Response : IResponse{}
internal class AnotherResponse : IResponse{}

那么下次调用时会发生什么:

new Test().TestMethod<AnotherResponse>();

根据您的需要,您可以将该方法更改为非通用方法:

interface ITest<TRequest>
{
    IResponse TestMethod(TRequest request);
}

或者添加第二个通用参数:

interface ITest<TRequest, TResponse>
    where TResponse : IResponse
{
    TResponse TestMethod(TRequest request);
}

class Test : ITest<Request, Response>
{
    public Response TestMethod(Request request) => new Response();
}
© www.soinside.com 2019 - 2024. All rights reserved.