简体   繁体   中英

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.

I don't see any problems with inferring that T is of type MyClass even without explicitly saying so

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.

To cut a long story short: you need to specify the type argument.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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