Information Technology Reference
In-Depth Information
implementations of all elements defined in the interface. You must imple-
ment all methods, supply any and all property accessors and indexers, and
define all events defined in the interface. You identify and factor reusable
behavior into interfaces. You use interfaces as parameters and return values.
Yo u a l s o h a v e m o r e c h a n c e s t o r e u s e c o d e b e c a u s e u n r e l a t e d t y p e s c a n i m p l e -
ment interfaces. What's more, it's easier for other developers to implement
an interface than it is to derive from a base class you've created.
What you can't do in an interface is provide implementation for any of
these members. Interfaces contain no implementation whatsoever, and
they cannot contain any concrete data members. You are declaring the
binary contract that must be supported by all types that implement an
interface. However, you can create extension methods on those interfaces
to give the illusion of an implementation for interfaces. The System
.Linq.Enumerable class contains more than 30 extension methods declared
on IEnumerable<T>. Those methods appear to be part of any type that
implements IEnumerable<T> by virtue of being extension methods. You
saw this in Item 8:
public static class Extensions
{
public static void ForAll<T>(
this IEnumerable <T> sequence,
Action <T> action)
{
foreach (T item in sequence)
action(item);
}
}
// usage
foo.ForAll((n) => Console .WriteLine(n.ToString()));
Abstract base classes can supply some implementation for derived types,
in addition to describing the common behavior. You can specify data
members, concrete methods, implementation for virtual methods, prop-
erties, events, and indexers. A base class can provide implementation for
some of the methods, thereby providing common implementation reuse.
Any of the elements can be virtual, abstract, or nonvirtual. An abstract
base class can provide an implementation for any concrete behavior; inter-
faces cannot.
 
Search WWH ::




Custom Search