ex-05-01

来自「Programming Csharp Source Code(代码) Prog」· 代码 · 共 67 行

TXT
67
字号
//Example 05-01: Using a derived class

using System;

public class Window
{
   // constructor takes two integers to
   // fix location on the console
   public Window(int top, int left)
   {
      this.top = top;
      this.left = left;
   }

   // simulates drawing the window
   public void DrawWindow()
   {
      Console.WriteLine("Drawing Window at {0}, {1}",
         top, left);
   }

   // these members are private and thus invisible
   // to derived class methods; we'll examine this 
   // later in the chapter
   private int top;
   private int left;
}

// ListBox derives from Window
public class ListBox : Window
{
   // constructor adds a parameter
   public ListBox(
      int top, 
      int left, 
      string theContents):
      base(top, left)  // call base constructor
   {
      mListBoxContents = theContents;
   }
    
   // a new version (note keyword) because in the
   // derived method we change the behavior
   public new void DrawWindow()
   {
      base.DrawWindow();  // invoke the base method
      Console.WriteLine ("Writing string to the listbox: {0}", 
         mListBoxContents);
   }
   private string mListBoxContents;  // new member variable
}

public class Tester
{
   public static void Main()
   {
      // create a base instance
      Window w = new Window(5,10);
      w.DrawWindow();

      // create a derived instance
      ListBox lb = new ListBox(20,30,"Hello world");
      lb.DrawWindow();
   }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?