Difference between IQueryable and Queryable
I haven't quite got my head around interfaces so thought I'd word th开发者_StackOverflowe question in a way that'd help me better understand it.
I'm following a tutorial which has had me make an IQueryable. Why couldn't I just make a Queryable?
Queryable
is just a static class that contains extension methods to the IQueryable<T>
interface. You wouldn't use Queryable
directly in your code but rather invoke its methods given an IQueryable<T>
instance.
Queryable
is a static class that provides some convenient and useful methods to anything implementing IQueryable
. You can't make it because it's already made. You need to make a new class that actually does what you want it to do, and implement IQueryable
so other code written to use IQueryable
(including Queryable
) knows how to use it.
An interface is a contract that defines methods and properties, but there is no implementation in an interface.
A class implements the interface by supplying implementation for everything that is defined in the interface.
As an interface has no implementation, you can't create an instance of one. You have to create an instance of a class that implements the interface.
However, you can have a reference of the interface type, but it will point to an actual object. When you use the interface reference, you can use everything that is defined in the interface, but if the class contains more methods, you can't reach them without casting the reference to the actual class.
An interface does not imply how the class will be coded, only how the interaction with that class will be defined.
There may be many different implementations of a class that can query but that's unimportant as long as the interaction with all of those classes is the same.
精彩评论