如何从泛型方法返回特定类型?

时间:2018-08-17 04:46:11

标签: c# generics methods parameters

我正在尝试模拟实用程序的泛型类,但是从使用泛型的方法返回特定类型时,我没有成功。我在下面的实现无法正常工作,编译器在抱怨。有人可以帮忙投射并返回我需要的特定对象吗?

public HttpResponse<TResponse> SubmitRequest<TResponse>(string serviceUri, HttpVerbEnum httpVerb, HttpContentTypeEnum contentType, NameValueCollection header)
{
    string RawResponse = "";
    HttpResponse<CreateSaleResponse> Response = new HttpResponse<CreateSaleResponse>(new CreateSaleResponse(), RawResponse, System.Net.HttpStatusCode.Created);
    return Response;
}

1 个答案:

答案 0 :(得分:0)

执行当前操作可能是抛出“无法隐式转换类型” 错误。如果您要返回一种特定类型,则该方法不需要支持泛型。

您似乎想要的是这样的东西,它使用您指定的类型:

<div class="field group_id required">
        <label for="group_id" class="label"><span><?php echo __('Group') ?></span></label>
        <div class="control">
            <select name="group_id">
                <?php foreach ($groups as $key => $data) { 
                    ?>
                <option value="<?php 
                echo $data['value']; ?>"><?php echo $data['label']; ?></option>
                <?php }?>
            </select>
        </div>
    </div>

您在调用方法时输入类型:

public HttpResponse<TResponse> SubmitRequest<TResponse>(string serviceUri, HttpVerbEnum httpVerb, HttpContentTypeEnum contentType, NameValueCollection header)
{
    string RawResponse = "";
    HttpResponse<TResponse> Response = new HttpResponse<TResponse>(new TResponse(), RawResponse, System.Net.HttpStatusCode.Created);
    return Response;
}

关于如何模拟(出于测试目的?),这取决于您使用的模拟库。

相关问题