OOP的三大支柱:(1)封装 (2) 继承 (3)多态
C#中的封装,这里说明一下静态类和属性。
静态类:静态的类,不能实例化,而且是密闭的,不能从它派生类型,也无构造方法。
静态类的作用:由于C#中不允许有全局方法,而有时候却恰恰需要一些工具类来实现一些比如数学计算的事情,这个时候静态类便派上了用场。
属性及其作用:罗凯老师在Java课上对属性的解释是“Property: something that holds data“。一般而言,客户希望在不使用方法的情况下访问对象的状态;但是类的设计者却想将类的状态隐藏在类成员中而让客户只能通过方法间接访问对象的状态。而属性满足了这两个目的: (1)为客户提供简单的“类似成员变量”的接口(2)同时为设计者提供了“使用方法来实现”的OO设计所必须的数据隐藏性。
属性写法如下:
1 using System; 2 3 class MyClass 4 { 5 public int property; 6 public int Property 7 { 8 get { return this.property; } 9 set { this.property = value; } 10 } 11 static void Main(string[] args) 12 { 13 MyClass Object = new MyClass(); 14 Object.Property = 5; 15 Console.WriteLine(Object.Property); 16 } 17 }
继承和多态总是分不开。
和C++一样,在C#中需要实现多态的函数需要声明virtual,且在派生类中需要声明override。
1 using System; 2 3 public class Animal 4 { 5 public virtual void Dance() 6 { 7 Console.WriteLine("Animals can dance"); 8 } 9 } 10 11 public class Pig: Animal 12 { 13 public override void Dance() 14 { 15 Console.WriteLine("Pigs can dance"); 16 } 17 } 18 19 public class Dog: Animal 20 { 21 public override void Dance() 22 { 23 Console.WriteLine("Dogs can dance"); 24 } 25 } 26 27 class Test 28 { 29 static void Main(string[] args) 30 { 31 Animal[] animals = new Animal[3]; 32 animals[0] = new Animal(); 33 animals[1] = new Pig(); 34 animals[2] = new Dog(); 35 foreach( Animal a in animals ) 36 { 37 a.Dance(); 38 } 39 } 40 }
输出结果为:
但是如果没有override的话,输出结果会是3个Animals can dance
如果没有virtual的话,编译器将不允许你重写。
关于new关键字:
如果派生类中的一个方法声明是new的话,那么它将和父类中同签名的方法没有关系,说白了就是两个函数。
1 using System; 2 3 public class Animal 4 { 5 public void Dance() 6 { 7 Console.WriteLine("Animals can dance"); 8 } 9 } 10 11 public class Pig: Animal 12 { 13 public new void Dance() 14 { 15 Console.WriteLine("Pigs can dance"); 16 } 17 } 18 19 class Test 20 { 21 static void Main(string[] args) 22 { 23 Animal a = new Animal(); 24 a.Dance(); 25 Animal b = new Pig(); 26 b.Dance(); 27 Pig c = new Pig(); 28 c.Dance(); 29 } 30 }
输出为:
可以看出当Pig强制转化为Animal的时候,会调用Animals的方法。
如果不写new的话,编译器会提出警告,不过运行结果是一样的,说明默认情况下编译器会认为是new。
贴一段代码以帮助理解:
1 using System; 2 3 public class A 4 { 5 public virtual void Dance() 6 { 7 Console.WriteLine("A can dance"); 8 } 9 } 10 11 public class B: A 12 { 13 public override void Dance() 14 { 15 Console.WriteLine("B can dance"); 16 } 17 } 18 19 public class C: B 20 { 21 public new virtual void Dance() 22 { 23 Console.WriteLine("C can dance"); 24 } 25 } 26 27 public class D: C 28 { 29 public override void Dance() 30 { 31 Console.WriteLine("D can dance"); 32 } 33 } 34 35 class Test 36 { 37 static void Main(string[] args) 38 { 39 A a = new D(); 40 A b = new B(); 41 C c = new D(); 42 A d = new A(); 43 a.Dance(); 44 b.Dance(); 45 c.Dance(); 46 d.Dance(); 47 } 48 }
输出结果应该是: