X hits on this document

794 views

0 shares

0 downloads

0 comments

299 / 396

C# LANGUAGE SPECIFICATION

the Paint method in TextBox hides the Paint method in Control, but it does not alter the mapping of Control.Paint onto IControl.Paint, and calls to Paint through class instances and interface instances will have the following effects

Control c = new Control(); TextBox t = new TextBox(); IControl ic = c; IControl it = t; c.Paint();// invokes Control.Paint(); t.Paint();// invokes TextBox.Paint(); ic.Paint();// invokes Control.Paint(); it.Paint();// invokes Control.Paint();

However, when an interface method is mapped onto a virtual method in a class, it is possible for derived classes to override the virtual method and alter the implementation of the interface. For example, rewriting the declarations above to

interface IControl { void Paint(); }

class Control: IControl { public virtual void Paint() {...} }

class TextBox: Control { public override void Paint() {...} }

the following effects will now be observed

Control c = new Control(); TextBox t = new TextBox(); IControl ic = c; IControl it = t; c.Paint();// invokes Control.Paint(); t.Paint();// invokes TextBox.Paint(); ic.Paint();// invokes Control.Paint(); it.Paint();// invokes TextBox.Paint();

Since explicit interface member implementations cannot be declared virtual, it is not possible to override an explicit interface member implementation. However, it is perfectly valid for an explicit interface member implementation to call another method, and that other method can be declared virtual to allow derived classes to override it. For example

interface IControl { void Paint(); }

class Control: IControl { void IControl.Paint() { PaintControl(); }

protected virtual void PaintControl() {...} }

286Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

Document info
Document views794
Page views794
Page last viewedSat Dec 03 21:58:20 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments