关于接口(Interface)

接口,其实是指类之间约定的协议,可以包含方法、属性、事件和索引

接口成员不允许使用访问修饰符号(public、private、protected、internal),所有的接口成员都是公共的。

接口用于描述一系列类的公共方法/公共属性,它不实现任何的方法或属性,只是告诉继承它的类们至少要实现那些功能。

接口的实际意义在于利用接口的多态性来更好增加代码的面向对象的特性。接口可以用来创建一系列相互关联或者相互依赖的对象,而不需要指定它们的实体。因此可以用来封装一些彼此具有一部分关联的对象实体,来交付给主程序使用。这种想法就叫做面向接口的编程思想。

using System;
using System.Collections.Generic;

namespace Test
{
    public interface IMoveable
    {
        void WindBlow();
    }
    public class Tree : IMoveable
    {
        public void WindBlow()
        {
            Console.WriteLine("tree float");
        }
    }
    public class Grass : IMoveable
    {
        public void WindBlow()
        {
            Console.WriteLine("grass wave");
        }
    }
    public class WindPass
    {
        public WindPass(IMoveable canMove)
        {
            canMove.WindBlow();

        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Tree T = new Tree();
            WindPass WP = new WindPass(T);
            IMoveable G = new Grass();
            WindPass WP_ = new WindPass(G);
        }
    }
}

 

posted @ 2017-03-11 15:15  丁香与醋栗  阅读(198)  评论(0编辑  收藏  举报