[英]Call a generic method without explicitly specifying the type-arguments
My controller-base has the following handler: 我的控制器库具有以下处理程序:
protected ActionResult HandleRequest<TRequest, TResponse, TViewModel>(Func<TRequest, TResponse> function, TRequest request)
where TRequest : BaseRequest
where TResponse : BaseResponse<TViewModel>
where TViewModel : BaseViewModel
{
var viewData = function(request);
return View(viewData);
}
Which is currently called like 目前被称为
return HandleRequest<HomeIndexGetRequest, HomeIndexGetResponse, HomeIndexGetViewModel>(GetData, request);
in my controller. 在我的控制器中。 The GetData-method looks like GetData方法看起来像
private static HomeIndexGetResponse GetData(HomeIndexGetRequest request)
{
return new HomeIndexGetResponse
{
ViewModel = new HomeIndexGetViewModel()
};
}
The HomeIndexGetResponse
signature is HomeIndexGetResponse
签名为
public class HomeIndexGetResponse : BaseResponse<HomeIndexGetViewModel>
And BaseResponse
is setup like 而且BaseResponse
的设置像
public abstract class BaseResponse<TViewModel> where TViewModel : BaseViewModel
Question: Is there any chance that I can call the HandleRequest without specifying the type-arguments explicitly? 问题:是否有可能可以在不显式指定类型参数的情况下调用HandleRequest?
return HandleRequest(GetData, request);
Playing around a bit I came up with the following solution which works as I need it. 玩了一点,我想出了以下解决方案,它可以根据需要工作。
New non-generic base class 新的非通用基类
public abstract class BaseResponse
Changed the BaseResponse to 将BaseResponse更改为
public abstract class BaseResponse<TViewModel> : BaseResponse where TViewModel : BaseViewModel
The handler changed to 处理程序更改为
protected ActionResult HandleRequest<TRequest, TResponse>(Func<TRequest, TResponse> function, TRequest request)
where TRequest : BaseRequest
where TResponse : BaseResponse
{
var viewData = function(request);
return View(viewData);
}
without the TViewModel type-argument. 没有TViewModel类型参数。
Finally, the controller looks like this 最后,控制器看起来像这样
return HandleRequest(GetData, request);
In the action, and the GetData
is implemented 在操作中,实现了GetData
private static BaseResponse GetData(HomeIndexGetRequest request)
{
return new HomeIndexGetResponse
{
ViewModel = new HomeIndexGetViewModel()
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.