【问题标题】:How to return a specific type from a generic method?如何从泛型方法返回特定类型?
【发布时间】:2018-08-17 04:46:11
【问题描述】:

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

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;
}

【问题讨论】:

  • the compiler is complaining 并且您没有添加编译器错误,因为您希望我们猜测?
  • 专业提示:编译器错误很重要,CLR 将它们包含在内,以提醒警惕的旅行者注意语法错误。很少有程序员能从内到外了解这门语言,所以我们学会依靠这些错误来为我们提供错误的线索,它们甚至是可搜索的,并且有常见问题的链接。作为一个在不知道您在做什么或坐在计算机前查看您的问题的人,我们更加依赖这些错误。请修改您的问题以包含将来的错误

标签: c# generics methods parameters


【解决方案1】:

做你目前正在做的事情可能会抛出一个“无法隐式转换类型”错误。如果您要返回一种特定类型,则该方法不需要支持泛型。

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

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;
}

调用方法时传入类型:

var response = SubmitRequest<SomeAppropriateType>(...);  // pass in your parameter values

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-15
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2023-01-12
    • 2012-07-11
    相关资源
    最近更新 更多