Implementing Interface Members Virtually

An implicitly implemented interface member is, by default, sealed. It must be
marked virtualor  abstractin the base class in order to be overridden. For example:

 1 public interface IUndoable { void Undo(); }
 2 public class TextBox : IUndoable
 3 {
 4 public virtualvoid Undo()
 5 {
 6 Console.WriteLine ("TextBox.Undo");
 7 }
 8 }
 9 public class RichTextBox : TextBox
10 {
11 public overridevoid Undo()
12 {
13 Console.WriteLine ("RichTextBox.Undo");
14 }
15 }

Calling the interface member through either the base class or the interface calls the
subclass’s implementation:

1 RichTextBox r = new RichTextBox();
2 r.Undo(); // RichTextBox.Undo
3 ((IUndoable)r).Undo(); // RichTextBox.Undo
4 ((TextBox)r).Undo(); // RichTextBox.Undo

 

posted @ 2013-06-06 15:51  futan57  阅读(224)  评论(0)    收藏  举报