简体   繁体   中英

Why can't the compiler resolve these generic types

If I have a method as such:

public void Foo<T1, T2>(T1 list)
    where T1 : IList<T2>
    where T2 : class
{
    // Do stuff
}

Now if I have:

IList<string> stringList = new List<string>();
List<object> objectList = new List<object>();
IList<IEnumerable> enumerableList = new List<IEnumerable>();

Then the compiler cannot resolve the generics to select and this fails:

Foo(stringList);
Foo(objectList);
Foo(enumerableList);

And you have to explicitly specify the generics to use as such:

Foo<IList<string>, string>(stringList);
Foo<IList<object>, object>(objectList);
Foo<List<object>, object>(objectList);
Foo<IList<IEnumerable>, IEnumerable>(enumerableList);

Generic method type inference deliberately does not make any deductions from the constraints. Rather, deductions are made from the arguments and the formal parameters , and then the deduced type arguments are checked against the constraints.

For a detailed discussion of some of the design issues around constraints and method signatures, including several dozen people telling me that I'm wrong to think that the existing design is sensible, see my article on the subject:

http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx

This is an exact copy of Eric Lippert's answer to a similar question .
I decided to copy it, because this question is more concise and clear.

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