Csharp/C Sharp/Class Interface/Override Virtual

Материал из .Net Framework эксперт
Версия от 11:39, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Class hierarchy: override and virtual

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 */
using System;
namespace Client.Chapter_5___Building_Your_Own_Classes
{
  public class MyMainClass13
  {
    static void Main(string[] args)
    {
      //The function called is based
      //upon the type called by new.
      B MyB = new C();
      MyB.Display();    //Calls C"s Display
    }
  }
  abstract class A
  {
    public abstract void Display();
  }
  class B: A
  {
    public override void Display()
    {
      Console.WriteLine("Class B"s Display Method");
    }
  }
  class C: B
  {
    public override void Display()
    {
      Console.WriteLine("Class C"s Display Method");
    }
  }
  class D: C
  {
    public override void Display()
    {
      Console.WriteLine("Class D"s Display Method");
    }
  }
}


Demonstrate a virtual method

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Demonstrate a virtual method. 
 
using System; 
 
class Base { 
  // Create virtual method in the base class.  
  public virtual void who() { 
    Console.WriteLine("who() in Base"); 
  } 
} 
 
class Derived1 : Base { 
  // Override who() in a derived class. 
  public override void who() { 
    Console.WriteLine("who() in Derived1"); 
  } 
} 
 
class Derived2 : Base { 
  // Override who() again in another derived class. 
  public override void who() { 
    Console.WriteLine("who() in Derived2"); 
  } 
} 
 
public class OverrideDemo { 
  public static void Main() { 
    Base baseOb = new Base(); 
    Derived1 dOb1 = new Derived1(); 
    Derived2 dOb2 = new Derived2(); 
 
    Base baseRef; // a base-class reference 
 
    baseRef = baseOb;  
    baseRef.who(); 
 
    baseRef = dOb1;  
    baseRef.who(); 
 
    baseRef = dOb2;  
    baseRef.who(); 
  } 
}


Demonstrates the use of a virtual method to override a base class method

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
// Virtual.cs -- Demonstrates the use of a virtual method to override
//               a base class method.
//
//               Compile this program with the following command line:
//                   C:>csc Virtual.cs
namespace nsVirtual
{
    using System;
    
    public class VirtualclsMain
    {
        static public void Main ()
        {
            clsBase Base = new clsBase();
            clsFirst First = new clsFirst();
            clsSecond Second = new clsSecond();
            Base.Show();
            First.Show();
            Second.Show ();
        }
    }
    class clsBase
    {
        public void Show ()
        {
            Describe ();
        }
        virtual protected void Describe ()
        {
            Console.WriteLine ("Called the base class Describe() method");
        }
    }
    class clsFirst : clsBase
    {
        override protected void Describe ()
        {
            Console.WriteLine ("Called the derived class Describe() method");
        }
    }
    class clsSecond : clsBase
    {
    }
}


Demonstrates the use of a virtual property to override a base class property

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
// VProp.cs -- Demonstrates the use of a virtual method to override
//             a base class method.
//
//             Compile this program with the following command line:
//                 C:>csc VProp.cs
namespace nsVirtual
{
    using System;
    
    public class VPropclsMain
    {
        static public void Main ()
        {
            clsBase Base = new clsBase();
            clsFirst First = new clsFirst();
            Base.SetString ("This should set the base class property");
            First.SetString ("This should set the derived class property");
            Console.WriteLine();
            Console.WriteLine (Base.GetString());
            Console.WriteLine (First.GetString());
        }
    }
    class clsBase
    {
  public void SetString (string str)
        {
            StrProp = str;
        }
        public string GetString ()
        {
            return (StrProp);
        }
        virtual protected string StrProp
        {
            get
            {
                Console.WriteLine ("Getting Base string");
                return (m_BaseString);
            }
            set
            {
                Console.WriteLine ("Setting Base string");
                m_BaseString = value;
            }
        }
        private string m_BaseString = "";
    }
    class clsFirst : clsBase
    {
        override protected string StrProp
        {
            get
            {
                Console.WriteLine ("Getting derived string");
                return (m_DerivedString);
            }
            set
            {
                Console.WriteLine ("Setting derived string");
                m_DerivedString = value;
            }
        }
        private string m_DerivedString = "";
   }
}


illustrates polymorphism

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example7_2.cs illustrates polymorphism
*/
using System;

// declare the MotorVehicle class
class MotorVehicle
{
  // declare the fields
  public string make;
  public string model;
  // define a constructor
  public MotorVehicle(string make, string model)
  {
    this.make = make;
    this.model = model;
  }
  // define the Accelerate() method (may be overridden in a
  // derived class)
  public virtual void Accelerate()
  {
    Console.WriteLine(model + " accelerating");
  }
}

// declare the Car class (derived from MotorVehicle)
class Car : MotorVehicle
{
  // define a constructor
  public Car(string make, string model) :
  base(make, model)
  {
    // do nothing
  }
  // override the base class Accelerate() method
  public override void Accelerate()
  {
    Console.WriteLine("Pushing gas pedal of " + model);
    base.Accelerate();  // calls the Accelerate() method in the base class
  }
}

// declare the Motorcycle class (derived from MotorVehicle)
class Motorcycle : MotorVehicle
{
  // define a constructor
  public Motorcycle(string make, string model) :
  base(make, model)
  {
    // do nothing
  }
  // override the base class Accelerate() method
  public override void Accelerate()
  {
    Console.WriteLine("Twisting throttle of " + model);
    base.Accelerate();  // calls the Accelerate() method in the base class
  }
}

public class Example7_2
{
  public static void Main()
  {
    // create a Car object and call the object"s Accelerate() method
    Car myCar = new Car("Toyota", "MR2");
    myCar.Accelerate();
    // create a Motorcycle object and call the object"s Accelerate() method
    Motorcycle myMotorcycle = new Motorcycle("Harley-Davidson", "V-Rod");
    myMotorcycle.Accelerate();
  }
}


Method override 3

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 class Dog
 {
     private int weight;
     // constructor
     public Dog(int weight)
     {
         this.weight = weight;
     }
     // override Object.ToString
     public override string ToString()
     {
         return weight.ToString();
     }
 }

 public class TesterOverride
 {
     static void Main()
     {
         int i = 5;
         Console.WriteLine("The value of i is: {0}", i.ToString());
         Dog milo = new Dog(62);
         Console.WriteLine("My dog Milo weighs {0} pounds", milo.ToString());
     }
 }


Polymorphism

 

using System;
public class MotorVehicle {
    public string make;
    public string model;
    public MotorVehicle(string make, string model) {
        this.make = make;
        this.model = model;
    }
    public virtual void Accelerate() {
        Console.WriteLine(model + " accelerating");
    }
}
public class Product : MotorVehicle {
    public Product(string make, string model) :
        base(make, model) {
    }
    public override void Accelerate() {
        Console.WriteLine("Pushing gas pedal of " + model);
        base.Accelerate();
    }
}
public class Motorcycle : MotorVehicle {
    public Motorcycle(string make, string model) :
        base(make, model) {
        // do nothing
    }
    public override void Accelerate() {
        Console.WriteLine("Twisting throttle of " + model);
        base.Accelerate();
    }
}

class MainClass {
    public static void Main() {
        Product myProduct = new Product("Toyota", "MR2");
        myProduct.Accelerate();
        Motorcycle myMotorcycle =
          new Motorcycle("Harley-Davidson", "V-Rod");
        myMotorcycle.Accelerate();
    }
}


Test Polymorphism Virtual Functions

/*
A Programmer"s Introduction to C# (Second Edition)
by Eric Gunnerson
Publisher: Apress  L.P.
ISBN: 1-893115-62-3
*/
// 01 - Object-Oriented Basics\Polymorphism and Virtual Functions
// copyright 2000 Eric Gunnerson
using System;
public PolymorphismVirtualFunctions
{
    public static void CallPlay(MusicServer ms)
    {
        ms.Play();
    }
    public static void Main()
    {
        MusicServer ms = new WinAmpServer();
        CallPlay(ms);
        ms = new MediaServer();
        CallPlay(ms);
    }
}
public abstract class MusicServer
{
    public abstract void Play();
}
public class WinAmpServer: MusicServer
{
    public override void Play() 
    {
        Console.WriteLine("WinAmpServer.Play()");
    }
}
public class MediaServer: MusicServer
{
    public override void Play() 
    {
        Console.WriteLine("MediaServer.Play()");
    }
}


Use virtual methods and polymorphism

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Use virtual methods and polymorphism. 
 
using System; 
 
class TwoDShape {  
  double pri_width;  // private 
  double pri_height; // private 
  string pri_name;   // private 
  
  // A default constructor.  
  public TwoDShape() {  
    width = height = 0.0;  
    name = "null";  
  }  
  
  // Parameterized constructor.  
  public TwoDShape(double w, double h, string n) {  
    width = w;  
    height = h;  
    name = n;  
  }  
  
  // Construct object with equal width and height.  
  public TwoDShape(double x, string n) {  
    width = height = x;  
    name = n;  
  }  
  
  // Construct an object from an object.  
  public TwoDShape(TwoDShape ob) {  
    width = ob.width;  
    height = ob.height;  
    name = ob.name;  
  }  
  
  // Properties for width, height, and name 
  public double width { 
    get { return pri_width; } 
    set { pri_width = value; } 
  } 
 
  public double height { 
    get { return pri_height; } 
    set { pri_height = value; } 
  } 
 
  public string name { 
    get { return pri_name; } 
    set { pri_name = value; } 
  } 
  
  public void showDim() {  
    Console.WriteLine("Width and height are " +  
                       width + " and " + height);  
  }  
  
  public virtual double area() {   
    Console.WriteLine("area() must be overridden");  
    return 0.0;  
  }   
}  
  
// A derived class of TwoDShape for triangles. 
class Triangle : TwoDShape {  
  string style; // private 
    
  // A default constructor.  
  public Triangle() {  
    style = "null";  
  }  
  
  // Constructor for Triangle.  
  public Triangle(string s, double w, double h) : 
    base(w, h, "triangle") {  
      style = s;   
  }  
  
  // Construct an isosceles triangle.  
  public Triangle(double x) : base(x, "triangle") {  
    style = "isosceles";   
  }  
  
  // Construct an object from an object.  
  public Triangle(Triangle ob) : base(ob) {  
    style = ob.style;  
  }  
  
  // Override area() for Triangle. 
  public override double area() {  
    return width * height / 2;  
  }  
  
  // Display a triangle"s style. 
  public void showStyle() {  
    Console.WriteLine("Triangle is " + style);  
  }  
}  
  
// A derived class of TwoDShape for rectangles.   
class Rectangle : TwoDShape {   
  // Constructor for Rectangle.  
  public Rectangle(double w, double h) :  
    base(w, h, "rectangle"){ }  
  
  // Construct a square.  
  public Rectangle(double x) :  
    base(x, "rectangle") { }  
  
  // Construct an object from an object.  
  public Rectangle(Rectangle ob) : base(ob) { }  
  
  // Return true if the rectangle is square. 
  public bool isSquare() {   
    if(width == height) return true;   
    return false;   
  }   
     
  // Override area() for Rectangle. 
  public override double area() {   
    return width * height;   
  }   
}  
  
public class DynShapes {  
  public static void Main() {  
    TwoDShape[] shapes = new TwoDShape[5];  
  
    shapes[0] = new Triangle("right", 8.0, 12.0);  
    shapes[1] = new Rectangle(10);  
    shapes[2] = new Rectangle(10, 4);  
    shapes[3] = new Triangle(7.0);  
    shapes[4] = new TwoDShape(10, 20, "generic"); 
  
    for(int i=0; i < shapes.Length; i++) {  
      Console.WriteLine("object is " + shapes[i].name);  
      Console.WriteLine("Area is " + shapes[i].area());  
  
      Console.WriteLine();    
    }  
  }  
}


Virtual and overload

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 */
using System;
namespace Client.Chapter_5___Building_Your_Own_Classes
{
  public class MyMainClass12 {
    static void Main(string[] args)
    {
      //The function called is based
      //upon the type called by new.
      B MyB = new C();
      D MyD = new D();
      MyB.Display();    //Calls C Display
      MyD.Display();    //Calls D Display
    }
  }
  public interface A
  {
    void Display();
  }
  class B: A
  {
    public virtual void Display()
    {
      Console.WriteLine("Class B"s Display Method");
    }
  }
  class C: B
  {
    public override void Display()
    {
      Console.WriteLine("Class C"s Display Method");
    }
  }
  class D: C
  {
    public override void Display()
    {
      Console.WriteLine("Class D"s Display Method");
    }
  }
}


Virtual keyword can be used to start a new inheritance ladder

 
using System;
public class Class1 {
    public static void Main(string[] strings) {
        BankAccount ba = new BankAccount();
        Test1(ba);
        SavingsAccount sa = new SavingsAccount();
        Test1(sa);
        Test2(sa);
        SpecialSaleAccount ssa = new SpecialSaleAccount();
        Test1(ssa);
        Test2(ssa);
        Test3(ssa);
        SaleSpecialCustomer ssc = new SaleSpecialCustomer();
        Test1(ssc);
        Test2(ssc);
        Test3(ssc);
        Test4(ssc);
    }
    public static void Test1(BankAccount account) {
        Console.Write("to Test(BankAccount)");
        account.Withdrawal(100);
    }
    public static void Test2(SavingsAccount account) {
        Console.Write("to Test(SavingsAccount)");
        account.Withdrawal(100);
    }
    public static void Test3(SpecialSaleAccount account) {
        Console.Write("to Test(SpecialSaleAccount)");
        account.Withdrawal(100);
    }
    public static void Test4(SaleSpecialCustomer account) {
        Console.Write("to Test(SaleSpecialCustomer)");
        account.Withdrawal(100);
    }
}
public class BankAccount {
    virtual public void Withdrawal(double dWithdrawal) {
        Console.WriteLine(" invokes BankAccount.Withdrawal()");
    }
}
public class SavingsAccount : BankAccount {
    override public void Withdrawal(double dWithdrawal) {
        Console.WriteLine(" invokes SavingsAccount.Withdrawal()");
    }
}
public class SpecialSaleAccount : SavingsAccount {
    new virtual public void Withdrawal(double dWithdrawal) {
        Console.WriteLine(" invokes SpecialSaleAccount.Withdrawal()");
    }
}
public class SaleSpecialCustomer : SpecialSaleAccount {
    override public void Withdrawal(double dWithdrawal) {
        Console.WriteLine
          (" invokes SaleSpecialCustomer.Withdrawal()");
    }
}


When a virtual method is not overridden, the base class method is used

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

/* When a virtual method is not overridden, 
   the base class method is used. */ 
 
using System; 
 
class Base { 
  // Create virtual method in the base class.  
  public virtual void who() { 
    Console.WriteLine("who() in Base"); 
  } 
} 
 
class Derived1 : Base { 
  // Override who() in a derived class. 
  public override void who() { 
    Console.WriteLine("who() in Derived1"); 
  } 
} 
 
class Derived2 : Base { 
  // This class does not override who(). 
} 
 
public class NoOverrideDemo { 
  public static void Main() { 
    Base baseOb = new Base(); 
    Derived1 dOb1 = new Derived1(); 
    Derived2 dOb2 = new Derived2(); 
 
    Base baseRef; // a base-class reference 
 
    baseRef = baseOb;  
    baseRef.who(); 
 
    baseRef = dOb1;  
    baseRef.who(); 
 
    baseRef = dOb2;  
    baseRef.who(); // calls Base"s who() 
  } 
}