- /*
- * Created by SharpDevelop.
- * User: Administrator
- * Date: 2008-9-8
- * Time: 8:24
- *
- * To change this template use Tools | Options | Coding | Edit Standard Headers.
- */
- using System;
- namespace TestNewMethodandOverride
- {
- class Shape
- {
- public Shape()
- {
- Console.WriteLine("Shape.Shape() is called");
- }
- public Shape(int r)
- {
- Console.WriteLine("Shape.Shape(int) is called");
- }
- public virtual void Draw()
- {
- Console.WriteLine("Shape.Draw() is called");
- }
- }
- class Circle:Shape
- {
- public Circle()
- {
- Console.WriteLine("Circle.Circle() is called");
- }
- public Circle(int r)
- {
- Console.WriteLine("Circle.Circle(int) is called");
- }
- public override void Draw()
- {
- Console.WriteLine("Circle.Draw() is called");
- }
- }
- class Rect:Shape
- {
- public Rect()
- {
- Console.WriteLine("Rect.Rect() is called");
- }
- public Rect(int r):base(r)
- {
- Console.WriteLine("Rect.Rect(int) is called");
- }
- public override void Draw()
- {
- Console.WriteLine("Rect.Draw() is called");
- }
- }
- class Strange:Shape
- {
- public Strange()
- {
- Console.WriteLine("Strange.Strange() is called");
- }
- public new void Draw()
- {
- Console.WriteLine("Strange.Draw() is called");
- }
- }
- class Program
- {
- public static void Main(string[] args)
- {
- Console.WriteLine("===new()===");
- //在子类默认构造函数被调用前父类的默认构造函数首先被调用
- Shape [] shape={new Circle(),new Rect(),new Strange()};
- //子类重载的方法和基类方法同一入口即基类方法“消失”了
- Console.WriteLine("===Draw()===");
- foreach(Shape i in shape)
- i.Draw();
- Console.WriteLine("===Strange===");
- //但是new方法例外,他和基类方法只是同名而不是同一入口
- //两个同名方法需要显式的调用
- Strange f = new Strange();
- f.Draw();
- ((Shape) f).Draw();
- Console.WriteLine("===Circle===");
- //在子类自定义构造函数被调用前父类的默认构造函数首先被调用
- //public Circle(int r)
- Circle c =new Circle(10);
- c.Draw();
- //通过基类调用方法(重载的)仍能正确映射到子类方法
- ((Shape) c).Draw();
- Console.WriteLine("===Rect===");
- //在子类自定义构造函数被调用前父类的默认构造函数首先被调用
- //除非子类自定义构造函数显示的调用基类自定义构造函数
- //public Cect(int r):base(r)
- Rect r =new Rect(10);
- r.Draw();
- //通过基类调用方法(重载的)仍能正确映射到子类方法
- ((Shape) r).Draw();
- Console.WriteLine("============");
- Console.Write("Press any key to continue . . . ");
- Console.ReadKey(true);
- }
- }
- }
通过基类调用子类中override 、 new 方法和构造函数的表现
最新推荐文章于 2020-07-13 18:58:26 发布