隐式公共方法:方法以及属性都只是声明而不包含代码体。
接口是把隐式公共方法和属性组合起来,以封装特定功能的一个集合。
声明接口不允许提供接口中任何成员的执行方式。
接口不能有构造方法和字段。
实现接口的类就必须要实现接口中的所有方法和属性。
接口的命名,前面要加一个大写字母‘I’。
一个类智能继承一个抽象类,却可以实现多个接口。
敏捷开发的思想,通过重构改善既有代码的设计。
//集合 using System.Collections; public partial class Form1 : Form { IList arrayAnimal; private void button3_Click(object sender, EventArgs e) { arrayAnimal = new ArrayList(); arrayAnimal.Add(new Cat("小花")); //...... MessageBox.Show(arrayAnimal.Count.ToString()); } }
ArrayList在对值类型进行装箱和拆箱时耗费了大量的计算。
//泛型 using System.Collections.Generic; public partial class Form1 : Form { IList<Animal> arrayAnimal; private void button3_Click(object sender, EventArgs e) { arrayAnimal = new List<Animal>(); arrayAnimal.Add(new Cat("小花")); //...... MessageBox.Show(arrayAnimal.Count.ToString()); } }
通常都是用泛型,因为可以获得类型安全的直接优点,而集合元素为值类型时,使用泛型不必对元素进行装箱。
//委托 class Cat { private string name; public Cat(string name) { this.name = name; } public delegate void CatShoutEventHandler(); //声明委托CatShoutEventHandler public event CatShoutEventHandler CatShout; //声明事件CatShout,它的事件类型是委托CatShoutEventHandler public void Shout() { Console.WriteLine("喵,我是{0}.", name); if(CatShout != null) { CatShout(); //表示当执行Shout()方法时,如果CatShout中有对象登记事件,则执行CatShout() } } } class Mouse { private string name; public Mouse(string name) { this.name = name; } //用来逃跑的方法 public void Run() { Console.WriteLine("老猫来了,{0}快跑!", name); } } static void Main(string[] args) { Cat cat = new Cat("Tom"); Mouse mouse1 = new Mouse("Jerry"); cat.CatShout += new Cat.CatShoutEventHandler(mouse1.Run); //表示将Mouse的Run方法通过实例化委托Cat.CatShoutEventHandler登记到Cat的事件CatShout当中。 cat.Shout(); Console.Read(); }