77家的会客2010

关于c#中多态的例子!(转)
Weather:十度有风天
/*
***这是一个非常简单的c#例子,但却涉及到了一些面向对象的高级概念
×××抽象类,子类如何继承并覆盖父类中的(抽象)方法,
***多态***
***/
using System;

public abstract class Shape
{
  public abstract void DrawYourself();
}

public class Triangle:Shape
{
  public override void DrawYourself()
   {
    Console.WriteLine("          *     ");
    Console.WriteLine("         * *    ");
    Console.WriteLine("        *   *   ");
    Console.WriteLine("       *     *  ");
    Console.WriteLine("      *--- * ");
   }
}
public class Circle:Shape
{
  public override void DrawYourself()
   {
    Console.WriteLine("    *******   ");
    Console.WriteLine("   *        * ");
    Console.WriteLine("  *          *");
    Console.WriteLine("  *          *");
    Console.WriteLine("   *        * ");
    Console.WriteLine("    *******   ");
   }
}
public class Rectangle:Shape
{
  public override void DrawYourself()
   {
    Console.WriteLine("-------------");
    Console.WriteLine("|____________|");
   }
}


public class DrawingEngine
{
  public Shape [] CreateDrawing()
   {
    int numberOfShapes=0;
    int shapeCounter=0;
    string choice;
    Shape [] drawing;

    Console.Write("How many shapes do you want in your drawing?");
    numberOfShapes=Convert.ToInt32(Console.ReadLine());
    drawing=new Shape[numberOfShapes];
    do
     {
      Console.Write("Choose next shape: C)ircle R)ectangle T)riangle: ");
      choice=Console.ReadLine().ToUpper();
      tch (choice)
       {
        case "C":
  drawing[shapeCounter]=new Circle();
  break;
 case "R":
  drawing[shapeCounter]=new Rectangle();
  break;
 case "T":
  drawing[shapeCounter]=new Triangle();
  break;
 default:
  Console.WriteLine("Invalid choice");
  shapeCounter--;
  break;
       }
      
      shapeCounter++;
     }while (shapeCounter<numberOfShapes);
    
    return drawing;
   }
  
  public void DrawDrawing(Shape [] drawing)
   {
    for (int i=0;i<drawing.Length;i++)
     {
      drawing[i].DrawYourself();
     }
   }
}

class TestDrawingEngine
{
  public static void Main()
   {
    Shape [] myDrawing;

    DrawingEngine myCAD=new DrawingEngine();
    string choice;

    do
     {
      Console.WriteLine("Please prepare to create drawing.");
      myDrawing=myCAD.CreateDrawing();

      do
       {
        Console.WriteLine("Here is your beautiful drawing.\n");
 myCAD.DrawDrawing(myDrawing);
 Console.WriteLine("\nDo you want to see it again? Y)es N)o");
 choice=Console.ReadLine().ToUpper();
       }while (choice != "N");
      
      Console.Write("Do you want to create another drawing? Y)es N)o :");
      choice=Console.ReadLine().ToUpper();
    
     }while (choice != "N");
   }
}
历史上的今天: [2007/03/31]Ghook.dll,svchost.exe病毒解决方法

[关于c#中多态的例子!(转)]的回复

Post a Comment~