简体   繁体   中英

Extension methods resolution IQueryable vs IEnumerable

Suppose I have a class which implements IQueryable<> (which inherits IEnumerable<> ) interface.

When I call Where() method on it, compiler resolves this call to IQueryable extensions although IEnumerable extensions also has Where() method defined.

The question is how the compiler understands which extension should be called?

C# spec has it described:

7.5.3.5 Better conversion target

Given two different types T1 and T2 , T1 is a better conversion target than T2 if at least one of the following holds:

  • An implicit conversion from T1 to T2 exists, and no implicit conversion from T2 to T1 exists

  • T1 is a signed integral type and T2 is an unsigned integral type.

Because there is a implicit conversion from IQueryable<T> to IEnumerable<T> , and there is no implicit conversion from IEnumerable<T> to IQueryable<T> , IQueryable<T> is a better conversion target, and takes precedence.

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