接口做为参数传递,传递的是实现了接口的对象;
接口作为类型返回,返回的是实现了接口的对象。
http://blog.csdn.net/tuziblog/article/details/4553922
接口的传递与返回就是围绕着上面的两句话展开的。
分别写两个例子来说明:
接口做为参数传递 :
- class Program
- {
- static void Main(string[] args)
- {
- Program p = new Program();
- Man m = new Man(); //这里,想实现谁接口里的方法,就实例化谁,然后在下边就传谁
- //Woman w = new Woman();
- p.Get(w); //传递的是实现了接口的对象
- Console.ReadLine();
- }
- public void Get(IPerson ipn) //接口做为参数传递
- {
- ipn.Say();
- }
- }
- /// <summary>
- /// 一个人类的接口
- /// </summary>
- public interface IPerson
- {
- void Say();
- }
- /// <summary>
- /// 一个男人的类
- /// </summary>
- public class Man : IPerson
- {
- public void Say()
- {
- Console.WriteLine("我是一个男人");
- }
- }
- /// <summary>
- /// 一个女人的类
- /// </summary>
- public class Woman : IPerson
- {
- public void Say()
- {
- Console.WriteLine("我是一个女人");
- }
- }
接口做为参数返回 :
- class Program
- {
- static void Main(string[] args)
- {
- string a = Console.ReadLine();
- Program pr = new Program();
- pr.Getsay(a);
- Console.ReadLine();
- }
- public Person Getsay(string a)
- {
- Person p = null;
- switch (a)
- {
- case "1":
- p = new Man();
- p.Say();
- break;
- case "2":
- p = new Woman();
- p.Say();
- break;
- }
- return p;
- }
- }
- public interface Person
- {
- void Say();
- }
- public class Man : Person
- {
- public void Say()
- {
- Console.WriteLine("我是男人");
- }
- }
- public class Woman : Person
- {
- public void Say()
- {
- Console.WriteLine("我是女人");
- }
- }
接口做为参数返回其实就是多态。
抽象类的传递和接口一样。不再说了