没有模板类的C#模板返回类型

时间:2018-08-10 13:01:27

标签: c# templates interface

我正在编写一个API客户端:

ApiRequest.cs:

public abstract class ApiRequest<T> : IApiRequest<T>
{
   #region Data Members

   private readonly Type _returnType;

   #endregion

   #region Properties

   public Type ReturnType
   {
      get
      {
         return _returnType;
      }
   }

   #endregion

   #region Constructor

   public ApiRequest()
   {
      _returnType = typeof( T );
   }

   #endregion

   public abstract HttpRequestMessage Build();

}

ApiResponse.cs:

public struct ApiResponse<T> : IApiResponse<T>
{

   #region Data Members 

   private readonly ApiRequest<T> _request;
   private readonly T _response;

   #endregion

   #region Properties

   public ApiRequest<T> Request
   {
      get
      {
         return _request;
      }
   }

   public T Content
   {
      get
      {
         return _response;
      }
   }

   #endregion

   public ApiResponse( ApiRequest<T> request, T response )
   {
      _request = request;
      _response = response;
   }

}

鉴于请求和响应类的布局方式,我希望客户端是完全通用的,并具有返回请求和响应的类型T的函数。我目前正在尝试:

public interface IApiClient
{
   IApiResponse<T> Request<IApiRequest<T>>( IApiRequest<T> request );
}

但是,我不允许在方法签名中使用T,因为IApiClient没有与其模板化。如何解决这个问题,以便我的ApiClient不必指定返回类型?

1 个答案:

答案 0 :(得分:0)

看起来您需要类似的东西

public interface IApiClient
{
    IApiResponse<T> Request<T>(IApiRequest<T> request);
}