简体   繁体   English

使用泛型清理代码

[英]Cleaning up code with generics

I am somewhat new to Generics and I came across this issue, I have repetitive code that I am trying to clean up. 我对Generics有点陌生,遇到了这个问题,我有一些重复的代码正在尝试清理。 The signature is different but the code being executed is the same, is there a way to pass in a generic type instead of having to specify each type in a new signature? 签名不同,但是执行的代码相同,是否有办法传递通用类型,而不必在新签名中指定每种类型?

public JsonResult<JsonData> GetServiceData(Func<IServiceResponse<IEnumerable<Order>>> func)
{
    var response = func();
    var jsonDataContainer = Mapper.Map<JsonData>(response);

    var result = GetJsonResult(jsonDataContainer);

    return result;
}

public JsonResult<JsonData> GetServiceData(Func<IServiceResponse<List<int>>> func)
{
    var response = func();
    var jsonDataContainer = Mapper.Map<JsonData>(response);

    var result = GetJsonResult(jsonDataContainer);

    return result;
}

public JsonResult<JsonData> GetServiceData(Func<IServiceResponse<User>> func)
{
    var response = func();
    var jsonDataContainer = Mapper.Map<JsonData>(response);

    var result = GetJsonResult(jsonDataContainer);

    return result;
}

It's hard to answer this question definitively, because you haven't specified the signature of Mapper.Map . 很难明确地回答这个问题,因为您尚未指定Mapper.Map的签名。

But, if Mapper.Map can take an IServiceResponse<T> of any type T , then this would work. 但是,如果Mapper.Map可以采用任何类型TIServiceResponse<T> ,那么它将起作用。

public JsonResult<JsonData> GetServiceData<T>(Func<IServiceResponse<T>> func)
{
    IServiceResponse<T> response = func();
    var jsonDataContainer = Mapper.Map<JsonData>(response);

    var result = GetJsonResult(jsonDataContainer);

    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM