Define an abstract class named Poly
1: public abstract class Poly
2: {3: private int r = 0;
4: public int R
5: { 6: get 7: {8: return r;
9: } 10: set 11: {12: r = value;
13: } 14: }15: public abstract double Area();
16: }CalArea class is derived from Poly calss and also overrides Area() method.
1: public class CalArea : Poly
2: {3: public override double Area()
4: {5: return R * R*Math.PI;
6: } 7: 8: }Here is the button-click event:
1: private void button1_Click(object sender, EventArgs e)
2: {3: CalArea calArea = new CalArea(); //實例化衍生類
4: Poly poly = calArea; //使用衍生類物件實例化抽像類
5: string str = textBox1.Text.Trim();
6: if (!string.IsNullOrEmpty(str))
7: {8: try
9: {10: poly.R = int.Parse(str);
11: textBox2.Text = poly.Area().ToString(); 12: }13: catch (Exception exc)
14: { 15: MessageBox.Show(exc.Message); 16: } 17: } 18: }Add an interface to Poly (abstract class), in which a string value should be return when calling QueryArea method
1: interface IArea
2: {3: string QueryArea();
4: }5: public abstract class Poly : IArea
6: {7: private int r = 0;
8: public int R
9: { 10: get 11: {12: return r;
13: } 14: set 15: {16: r = value;
17: } 18: }19: public abstract double Area();
20: public string QueryArea() // 實作IArea
21: {22: return Area().ToString();
23: } 24: 25: }And button click event is shown below
1: private void button1_Click(object sender, EventArgs e)
2: {3: CalArea calArea = new CalArea(); //實例化衍生類
4: Poly poly = calArea; //使用衍生類物件(等號右邊)實例化抽像類(等號左邊)
5: string str = textBox1.Text.Trim();
6: if (!string.IsNullOrEmpty(str))
7: {8: try
9: {10: poly.R = int.Parse(str); // 相當於執行 calArea.R
11: textBox2.Text = poly.QueryArea(); // 取得面積字串, 與下一行程式碼等效
12: //textBox2.Text = calArea.QueryArea();
13: }14: catch (Exception exc)
15: { 16: MessageBox.Show(exc.Message); 17: } 18: } 19: }文章標籤
全站熱搜
