面向对象
这篇篇文章我主要通过两个例子(计算器和猜拳游戏)来理解面向对象。
使用面向对象编程,关键的是要找出重复的东西,然后把它抽象出来,进行封装。所以,我们先来看下计算器计算的时候,哪些是重复的。重复的可作为属性。
先看计算器的例子。我们先模拟下计算的场景。当用户打开计算器的时候,先需要输入第一个要计算的数字,然后选择运算符,接下来输入第二个要计算的数字,最后得出计算结果。这里面,每次计算的时候,都涉及到要输入的数字,运算符,这三个是变量,所以我们把它们抽象出来,放到一个计算类Calc中。然后在点击计算的时候运算即可。代码如下:
Calc类:
1 public class Calc 2 { 3 public double Number1 { get; set; } 4 public double Number2 { get; set; } 5 6 public double Calculate(string sign) 7 { 8 double r; 9 switch (sign) 10 { 11 case "+": 12 r = this.Number1 + this.Number2; 13 break; 14 case "-": 15 r = this.Number1 - this.Number2; 16 break; 17 case "*": 18 r = this.Number1 * this.Number2; 19 break; 20 case "/": 21 r = this.Number1 / this.Number2; 22 break; 23 default: 24 throw new Exception("参数错误!"); 25 } 26 return r; 27 } 28 }
计算方法:
1 namespace 面线对象实现计算器 2 { 3 public partial class Form1 : Form 4 { 5 public Form1() 6 { 7 InitializeComponent(); 8 } 9 10 private void btnEquals_Click(object sender, EventArgs e) 11 { 12 Calc c = new Calc(); 13 c.Number1 = Convert.ToDouble(txtNumber1.Text); 14 c.Number2 = Convert.ToDouble(txtNumber2.Text); 15 16 string sign = cmbSign.Text; 17 18 try 19 { 20 txtResult.Text = c.Calculate(sign).ToString(); 21 } 22 catch (Exception ex) 23 { 24 MessageBox.Show(ex.Message); 25 } 26 27 } 28 } 29 }