使用通用类型定义类

时间:2016-08-01 13:24:25

标签: c#

我有以下类定义:

public class AsyncValidationRequestHandler<TRequest, TResponse> : IAsyncRequestHandler<TRequest, TResponse> 
    where TRequest : IAsyncRequest<TResponse> { }

但是我需要将TResponse定义为Envelope,其中Envelope是:

public class Envelope<T> { }

我尝试了以下内容:

public class AsyncValidationRequestHandler<TRequest, TResponse> : IAsyncRequestHandler<TRequest, TResponse> 
    where TRequest : IAsyncRequest<TResponse> 
    where TResponse : Envelope<TModel> { }

基本上,我将信封定义为:

ModalA modelA = new ModelA();
Envelope<ModelA> envelopeA = new Envelope<ModelA>();

ModalB modelB = new ModelB();
Envelope<ModelB> envelopeB = new Envelope<ModelB>();

而且我知道我的回应总是一个信封......

但是我的代码没有编译。我收到错误:

The type or namespace name 'TModel' could not be found (are you missing a using directive or an assembly reference?)    

如何解决这个问题?我需要一个界面吗?

1 个答案:

答案 0 :(得分:4)

您还需要将TModel声明为通用参数:

public class AsyncValidationRequestHandler<TRequest, TResponse, TModel> : IAsyncRequestHandler<TRequest, TResponse> 
    where TRequest : IAsyncRequest<TResponse> 
    where TResponse : Envelope<TModel> { }