C #: Why does generic type inference not work when there are several type arguments?

Here are two examples:

This works great:

void Main() { var list = Queryable.ProjectTo(typeof(Projection)); } public static class QueryableExtensions { public static ProjectionList<T> ProjectTo<T>(this IQueryable<T> queryable, Type projectionType) { return new ProjectionList<T>(queryable, projectionType); } } 

This causes the following error:

Using the generic method 'QueryableExtensions.ProjectTo (System.Linq.IQueryable)' requires 2 arguments of type

 void Main() { var list = Queryable.ProjectTo<Projection>(); } public static class QueryableExtensions { public static ProjectionList<T, P> ProjectTo<T, P>(this IQueryable<T> queryable) { return new ProjectionList<T, P>(queryable); } } 

Of course, the first example requires 1 type argument, however, the compiler can understand what it is, so I do not need to provide it. In the second example, 2 type arguments are required, but the compiler knows what T is, so it requires not only one that cannot be output?

For the record, I use the first example, just fine in my code, but I like the syntax of the second much better, and there may be times when I would like to have a common type of projection. Is there any way to achieve this, or am I barking the wrong tree?

Thanks!

+4
source share
2 answers

The problem is not two parameters, but where does it get it from? The general output of a parameter considers only parameters and, in particular, does not consider the types of data returned. There is nothing in the parameters that P. could offer. It is required that either the general type inference provide all of them, or all of them are specified explicitly. It is interesting to note that “mumble-typing” was once mentioned, which, as I interpret it (since it was never completely defined), would allow you to mix and match as you want. Imagine:

 blah.ProjectTo<?,SomeType>(); 

(the exact syntax does not matter, since this language function does not exist), but it will mean "there are two genericmtype arguments: you (the compiler) evaluate the first parameter, the second - SomeType".

+5
source

This is because the general output of a parameter only works with input parameters. In your second example, the parameter P appears only in the return type, so the output cannot work. Therefore, when you write:

 var list = Queryable.ProjectTo<Projection>(); 

T Projection , but what is P for you?

But even if you write:

 ProjectionList<Projection, FooBar> list = Queryable.ProjectTo(); 

it still doesn't work.

+4
source

Source: https://habr.com/ru/post/1397334/


All Articles