简体   繁体   English

如果返回通用类型,则无法推断

[英]Cannot infer generic type if it is returned

I have a very simple extension method (it's probably irrelevant though that it is extension and would be the same for ordinary ones): 我有一个非常简单的扩展方法(尽管它是扩展名,与普通扩展名相同,这可能无关紧要):

public static T Content<T>(this HttpResponseMessage response)
{
    var content = (ObjectContent<T>) response.Content;
    return (T) content.Value;
}

Now I do use it like that: 现在,我确实像这样使用它:

MyContent content = response.Content();

But I get the error that type cannot be inferred from the usage, so I have to do this: 但是我收到了一个错误,即无法从用法中推断出类型,因此我必须这样做:

MyContent content = response.Content<MyContent>();

Is this just a missing feature that it cannot infer or I am doing something wrong here? 这仅仅是一个无法推断的缺失功能,还是我在这里做错了什么? I don't see any problems with inferring that T is of type MyContent even without explicitly saying so, though of course I did not write the compiler and don't know all the details. 我没有看到推断TMyContent类型的任何问题,即使没有明确说明也是如此,尽管我当然没有编写编译器,也不知道所有细节。

I don't see any problems with inferring that T is of type MyClass even without explicitly saying so 我没有发现推断T是MyClass类型的任何问题,即使没有明确说明也是如此

Well, the problem is that the language isn't specified that way at all. 好吧,问题在于根本没有指定这种语言。 Generic type inference is performed based on the arguments. 泛型类型推断是基于参数执行的。 A method invocation expression is a kind of expression that always has a type - and resolving which method overload is being used and what the generic type arguments are is part of establishing that type. 方法调用表达式是一种始终具有类型的表达式-解决使用哪种方法重载以及泛型类型参数是建立该类型的一部分。 How the result is used is simply not part of overload resolution or type inference. 结果的使用方式根本属于重载解析或类型推断的一部分。

It is used when performing conversions from anonymous functions, method groups and the null literal - those are expressions which don't have types in themselves, but are merely convertible to the appropriate type. 执行从匿名函数,方法和组null文本转换,当它用于-这些都是不具有类型本身表达式,但仅仅是转换为适当的类型。

To cut a long story short: you need to specify the type argument. 简而言之:您需要指定type参数。

Note that you don't need to write the compiler to get all the details - that's what the language specification is for. 请注意,您无需编写编译器即可获得所有详细信息-这就是语言规范的用途。 The most recently published specification is C# 5 . 最新发布的规范是C#5

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

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