第1關:繼承

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace K1 { public abstract class Shape { public abstract int Area(); //獲取形狀面積 } /********** Begin *********/ class Square : Shape { int side = 0; public Square(int _side) { side = _side; } public override int Area(){ return side * side; } } /********** End *********/ public class myCaller { public static void Main(string[] args) { for (int i = 0; i < 4; i++) { string side = Console.ReadLine(); Square s = new Square(Convert.ToInt32(side)); Console.WriteLine("Square Area:" + s.Area()); } } } }
第2關:多態

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace K2 { public abstract class Shape { public abstract int Area(); //獲取形狀面積 } /********** Begin *********/ //圓形類和正方形類 class Circular : Shape { int radius = 0; public Circular(int _radius) { radius = _radius; } public override int Area(){ const int PI = 3; return PI * radius * radius; } } class Square : Shape { int side = 0; public Square(int _side) { side = _side; } public override int Area(){ return side * side; } } /********** End *********/ public class myCaller { public static void Main(string[] args) { Circular c = new Circular(4); Square s = new Square(4); Shape shape1 = s; Shape shape2 = c; Console.WriteLine("Square Area:" + shape1.Area()); Console.WriteLine("Circular Area:" + shape2.Area()); } } }
第3關:運算符的重載

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace K3 { public class Community { private int number; //人數 public Community(int number) { this.number = number; } /********** Begin *********/ //重載+運算符 public static int operator +(Community a, Community b) { return a.number+b.number; } /********** End *********/ } public class myCaller { public static void Main(string[] args) { Community violin = new Community(50); //小提琴社 Community cello = new Community(27); //大提琴社 int total = violin + cello; Console.WriteLine("The number of participants in this event is:" + total); } } }
第4關:interface接口

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace K4 { /********** Begin *********/ //定義接口IColor和IShape interface IColor { } interface IShape { } /********** End *********/ class myBox : IColor, IShape { private string color; private string shape; public void showBox() { Console.WriteLine("box color:" + color); Console.WriteLine("box shape:" + shape); } /********** Begin *********/ //實現接口函數 internal void setColor(string v) { this.color=v; } internal void setShape(string v) { this.shape = v; } /********** End *********/ } public class myCaller { public static void Main(string[] args) { myBox box = new myBox(); box.setColor("Grey"); //調用實現的接口函數 box.setShape("Cube"); box.showBox(); } } }
我要罵人了,我怎么這么蠢哦!