本文實(shí)例講述了C#基于簡(jiǎn)單工廠模式實(shí)現(xiàn)的計(jì)算器功能。分享給大家供大家參考,具體如下:
子類擁有父類除私有之外的所有屬性字段和方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 工廠方法實(shí)現(xiàn)計(jì)算器 { /// <summary> /// 計(jì)算器類(抽象類,由子類重寫) /// </summary> public abstract class Calculator { public double Number1 { get ; set ; } public double Number2 { get ; set ; } public Calculator() { } public Calculator( double a, double b) { this .Number1=a; this .Number2=b; } /// <summary> /// 計(jì)算 /// </summary> /// <returns></returns> public abstract double jsuan(); } /// <summary> /// 加法類 /// </summary> public class jiafaDll:Calculator //子類擁有父類除私有之外的所有屬性字段和方法 { public jiafaDll() { } public jiafaDll( double a, double b) : base (a, b) //調(diào)用父類帶兩個(gè)參數(shù)的構(gòu)造函數(shù),來(lái)初始化Number1 和Number2 (注意:因?yàn)閖ianfaDll類繼承了Calculator,所以jianfaDll類是有Number1,和Number2兩個(gè)屬性的) { } /// <summary> /// 重寫父類的jsuan方法 /// </summary> /// <returns></returns> public override double jsuan() { return Number1 + Number2; } } /// <summary> /// 減法類 /// </summary> public class jianfaDll : Calculator { public jianfaDll() { } public jianfaDll( double a, double b) : base (a, b) { } public override double jsuan() { return Number1 - Number2; } } class Program { static void Main( string [] args) { Console.WriteLine( "請(qǐng)輸入第一個(gè)數(shù)" ); double number1 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine( "請(qǐng)輸入一個(gè)操作符" ); string caozuofu = Console.ReadLine(); Console.WriteLine( "請(qǐng)輸入第二個(gè)數(shù)" ); double number2 = Convert.ToDouble(Console.ReadLine()); Calculator c= null ; switch (caozuofu) { case "+" : c = new jiafaDll(number1, number2); break ; case "-" : c = new jianfaDll(number1, number2); break ; } double i= c.jsuan(); Console.WriteLine(i); Console.ReadKey(); } } } |
希望本文所述對(duì)大家C#程序設(shè)計(jì)有所幫助。
原文鏈接:http://blog.csdn.net/fanbin168/article/details/45788277