Tải bản đầy đủ (.ppt) (34 trang)

Chương 7: Working with Interfaces pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (400.47 KB, 34 trang )

Chapter 7. Working with
Interfaces
Hoang Anh Viet

Hanoi University of Technology
1
MicrosoftMicrosoft
Objectives
“In this chapter you will learn how to define types that support
multiple behaviors, how to discover these behaviors at runtime, and
how to selectively hide particular behaviors using explicit interface
implementation. In addition to examining a number of predefined
.NET interface types, you will also learn how to make use of custom
interfaces to build an ad hoc event architecture.”

Interfaces Define Types

Defining Interfaces

Implementing Interfaces

Interface Member Matching Rules

Explicit Interface Implementation with Value Types

Versioning Considerations

Contracts

Choosing Between Interfaces and Classes
2


MicrosoftMicrosoft
Roadmap

7.1 Interfaces Define Types

7.2 Defining Interfaces

7.3 Implementing Interfaces

7.4 Interface Member Matching Rules

7.5 Explicit Interface Implementation with Value Types

7.6 Versioning Considerations

7.7 Contracts

7.8 Choosing Between Interfaces and Classes
3
MicrosoftMicrosoft
7.1 Interfaces Define Types

An interface declaration defines a reference type

Within variables of this type, you can store a reference to an
object that implements the contract of the interface type

Example: declare interface IUIControl
4
public interface IUIControl

{
void Paint();
}
public class Button : IUIControl
{
public void Paint() { // Paint the Button }
}
public class ListBox : IUIControl
{
public void Paint() { // Paint the Listbox }
}
This interface defines a contract,
which states that any type that
implements this interface must
implement the Paint() method.
MicrosoftMicrosoft
Roadmap

7.1 Interfaces Define Types

7.2 Defining Interfaces

7.3 Implementing Interfaces

7.4 Interface Member Matching Rules

7.5 Explicit Interface Implementation with Value Types

7.6 Versioning Considerations


7.7 Contracts

7.8 Choosing Between Interfaces and Classes
5
MicrosoftMicrosoft
7.2 Defining Interfaces

What is an Interface?

Defines the signatures for a set of public members that
will be available through an object instance

Classes provide implementation details

Classes may implement multiple interfaces
6
MicrosoftMicrosoft
Why use Interfaces?

Ensure consistency in similar classes

Classic example: data access

Allow client applications to write generic code against an
interface

Implementation can be completely with minimum carnage on the
client

Remember: code to the interface – not the

implementation!
7
MicrosoftMicrosoft
7.2 Defining Interfaces

What Can Be in an Interface?

Interface = purely abstract class; only signatures, no
implementation.

May contain methods, properties, indexers and events (no
fields, constants, constructors, destructors, operators, nested
types).

Interface members are implicitly public abstract (virtual).

Interface members must not be static.
8
public delegate void DBEvent( IMyDatabase sender );
public interface IMyDatabase : ISerializable, IDisposable
{
void Insert( object element ); //method
int Count { get; } //property
object this[ int index ] { get; set; } //indexer
event DBEvent dbChanged; //event
}
MicrosoftMicrosoft
7.2 Defining Interfaces

Interface Inheritance and Member Hiding


Interfaces support multiple inheritance from other interfaces in
the syntactic sense
9
public interface IUIControl
{
void Paint();
}
public interface IEditBox : IUIControl
{
}
public interface IDropList : IUIControl
{
}
public class ComboBox : IEditBox, IDropList
{
public void Paint() { // paint implementation for ComboBox }
}
ComboBox implements both of those
interfaces IEditBox and IDropList, it
must implement the union of all the
methods declared in the interfaces it
directly implements, plus the interfaces
those interfaces implement recursively
MicrosoftMicrosoft
7.2 Defining Interfaces

Interface Inheritance and Member Hiding

Sometimes, you need to declare a method in an interface that

hides a method in an inherited interface. You must use the new
keyword if you want to keep the compiler from complaining
about it with a warning.

Eg. When the IEditBox interface declares the Paint method
using the new keyword, it is said to hide the Paint method
declared in IUIControl.
10
using System;
public interface IUIControl
{
void Paint();
}
public interface IEditBox : IUIControl
{
new void Paint();
}
public interface IDropList : IUIControl
{
}
public class ComboBox : IEditBox, IDropList
{
public void Paint()
{
Console.WriteLine("ComboBox.IEditBox.Paint()");
}
}
public class EntryPoint
{
static void Main()

{
ComboBox cb = new ComboBox();
cb.Paint();
((IEditBox)cb).Paint();
((IDropList)cb).Paint();
((IUIControl)cb).Paint();
}
}
ComboBox.cs
Use the new keyword
to declare a Paint method
whose signature is exactly
that of the one in IUIControl
In all calls to the Paint method in the
Main method, it always boils down to
a call on ComboBox.Paint
Because the set of required methods
that ComboBox must implement are
merged together into one set.
11
MicrosoftMicrosoft
Roadmap

7.1 Interfaces Define Types

7.2 Defining Interfaces

7.3 Implementing Interfaces

7.4 Interface Member Matching Rules


7.5 Explicit Interface Implementation with Value Types

7.6 Versioning Considerations

7.7 Contracts

7.8 Choosing Between Interfaces and Classes
12
MicrosoftMicrosoft
7.3 Implementing Interfaces

There are 2 way for implementing interfaces

Implicit implementations (default): The method
implementations are part of the public contract of the class but
also implement the interface implicitly.

Explicit implementations: the method implementations are
private to the implementing class and don’t become part of the
public interface. Explicit implementation provides some
flexibility, especially when implementing two interfaces that have
methods with the same name in them.
13
MicrosoftMicrosoft
7.3.1 Implicit Interface Implementation

When a concrete type implements the methods in
inherited interfaces, and those methods are marked
public, it’s known as implicit interface implementation.

14
public interface IUIControl
{
void Paint();
}
public class StaticText : IUIControl
{
void Paint();
// !!! WON'TCOMPILE !!!
}
NOT VALID!!!
public interface IUIControl
{
void Paint();
}
public class StaticText : IUIControl
{
public void Paint(); /*Notice
that we've added 'public' to the
method declaration*/
}
VALID
MicrosoftMicrosoft
7.3.2 Explicit Interface Implementation

When you implement interface methods explicitly, not only do
you add the interface name followed by a dot before the method
name, but you also remove the access modifier. This keeps it
from being in the public contract for ComboBox.
15

public class ComboBox : IEditBox, IDropList
{
void IEditBox.Paint()
{ Console.WriteLine("ComboBox.IEditBox.Paint()");
}
void IUIControl.Paint()
{ Console.WriteLine("ComboBox.IUIControl.Paint()");
}
public void Paint()
{
((IUIControl)this).Paint();
}
}
using System;
public interface IUIControl
{
void Paint();
void Show();
}
public interface IEditBox : IUIControl
{
void SelectText();
}
public interface IDropList : IUIControl
{
void ShowList();
}
public class ComboBox : IEditBox, IDropList
{
public void Paint() { }

public void Show() { }
public void SelectText() { }
public void ShowList() { }
}
public class FancyComboBox : ComboBox
{
public void Paint() { }
}
public class EntryPoint
{
static void Main() {
FancyComboBox cb = new FancyComboBox();
}
}
7.3.3 Overriding Interface Implementations in Derived Classes
FancyComboBox.cs
FancyComboBox.Paint
hides inherited member
ComboBox.Paint
16
using System;
public interface IUIControl
{
void Paint();
void Show();
}
public interface IEditBox : IUIControl
{
void SelectText();
}

public interface IDropList : IUIControl
{
void ShowList();
}
public class ComboBox : IEditBox, IDropList
{
public void Paint() { Console.WriteLine( "ComboBox.Paint()" ); }
public void Show() { }
public void SelectText() { }
public void ShowList() { }
}
public class FancyComboBox : ComboBox, IUIControl
{
public new void Paint() {
Console.WriteLine( "FancyComboBox.Paint()" );
}
}
public class EntryPoint
{
static void Main() {
FancyComboBox cb = new FancyComboBox();
cb.Paint();
((IEditBox)cb).Paint();
}
}
7.3.3 Overriding Interface Implementations in Derived Classes
FancyComboBox2.cs
FancyComboBox is planning
to reimplement the IUIControl
interface

Use the new keyword for
FancyComboBox.Paint, since
it hides CombBox.Paint
17
using System;
public interface IUIControl
{
void Paint();
void Show();
}
public interface IEditBox : IUIControl
{
void SelectText();
}
public interface IDropList : IUIControl
{
void ShowList();
}
public class ComboBox : IEditBox, IDropList
{
public virtual void Paint() { Console.WriteLine( "ComboBox.Paint()" ); }
public void Show() { }
public void SelectText() { }
public void ShowList() { }
}
public class FancyComboBox : ComboBox
{
public override void Paint()
{
Console.WriteLine("FancyComboBox.Paint()");

}
}
public class EntryPoint
{
static void Main()
{
FancyComboBox cb = new FancyComboBox();
cb.Paint();
((IUIControl)cb).Paint();
((IEditBox)cb).Paint();
}
}
7.3.3 Overriding Interface Implementations in Derived Classes
FancyComboBox3.cs
Implementing the IUIControl
interface in ComboBox using virtual
methods would make the previous
problem a lot easier to solve
18
MicrosoftMicrosoft
7.3.4 Beware of Side Effects of Value Types
Implementing Interfaces

Value types can implement interfaces: make side effect

If you cast a value type to an interface type, you’ll incur a boxing
penalty.

Even worse, if you modify the value via the interface reference,
you’re modifying the boxed copy and not the original.

19
MicrosoftMicrosoft
Roadmap

7.1 Interfaces Define Types

7.2 Defining Interfaces

7.3 Implementing Interfaces

7.4 Interface Member Matching Rules

7.5 Explicit Interface Implementation with Value Types

7.6 Versioning Considerations

7.7 Contracts

7.8 Choosing Between Interfaces and Classes
20
MicrosoftMicrosoft
7.4 Interface Member Matching Rules

The interface member matching rules for C# are pretty
straightforward and boil down to some simple rules.

The rules of the CLR: To find the implementation for
SomeMethod on ISomeInterface, start at the bottom of the
hierarchy and search for the first type that implements the
interface in question.


The C# method-matching rules: when you walk up the hierarchy,
you short-circuit the search once you find a method at a
particular level.
21
using System;
public interface IComparable
{
int CompareTo(object obj);
}
public struct SomeValue : IComparable
{
public SomeValue( int n )
{
this.n = n;
}
public int CompareTo( object obj )
{
if( obj is SomeValue )
{
SomeValue other = (SomeValue) obj;
return n - other.n;
}
else
{
throw new ArgumentException( "Wrong Type!" );
}
}
private int n;
}

public class EntryPoint
{
static void Main()
{
SomeValue val1 = new SomeValue(1);
SomeValue val2 = new SomeValue(2);
Console.WriteLine(val1.CompareTo(val2));
}
}
7.5 Explicit Interface Implementation with Value Types
IComparable.cs
Icomparable is a general-use
interfaces that take parameters
in the form of a reference
to System.Object
CompareTo method
accepts general type
First, since CompareTo takes an object reference,
val2must be boxed at the point of the method call.
Need to cast the val1 value into an
IComparable interface, which
would incur a boxing penalty
But once you’re inside the CompareTomethod,
the boxing nightmare is still not over.
22
using System;
public struct SomeValue : IComparable
{
public SomeValue(int n)
{

this.n = n;
}
int IComparable.CompareTo(object obj)
{
if (obj is SomeValue)
{
SomeValue other = (SomeValue)obj;
return n - other.n;
}
else
{
throw new ArgumentException("Wrong Type!");
}
}
public int CompareTo(SomeValue other)
{
return n - other.n;
}
private int n;
}
public class EntryPoint
{
static void Main()
{
SomeValue val1 = new SomeValue(1);
SomeValue val2 = new SomeValue(2);
Console.WriteLine(val1.CompareTo(val2));
}
}
7.5 Explicit Interface Implementation with Value Types

IComparable2.cs
A type-safe version of
the CompareTo
method
There is absolutely no boxing in the call to
CompareTo. That’s because the compiler picks
the one with the best match for the type.
23
MicrosoftMicrosoft
Roadmap

7.1 Interfaces Define Types

7.2 Defining Interfaces

7.3 Implementing Interfaces

7.4 Interface Member Matching Rules

7.5 Explicit Interface Implementation with Value Types

7.6 Versioning Considerations

7.7 Contracts

7.8 Choosing Between Interfaces and Classes
24
MicrosoftMicrosoft
7.6 Versioning Considerations


Consider interface as contract, or standard

Standards normally have version numbers attached to them,
and when they are revised, the version number is incremented.

For new revisions of your interface, you could simply give it a
new name - the key point being that you never change the
original interface.

In reality, if your interface definitions live within a versioned
assembly, you may define a newer version of the same
interface, even with the same name, in an assembly with the
same name but with a new version number. The assembly
loader will resolve and load the proper assembly at run-time.
25

×