C# 如何创建接口以及使用接口的简单Demo(转载!)

//No:1  首先,我们要封装一个接口,接口中不要实现具体的方法(说白了这就是一个架子而已!)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    interface Ipeople //接口声明:
    {
        int w
        {
            get;
            set;
        }
        int h
        {
            get;
            set;
        }
    }

//No:2 接口的调用
    class MyPoint : Ipeople //实现接口
    {

        //这里的类就必须要实现接口中未实现的方法
        private int myW;
        private int myH;
        public MyPoint(int w, int h)
        {
            myW = w;
            myH = h;
        }
        public int w
        {
            get { return myW; }
            set { myW = value;}
        }
        public int h
        {
            get { return myH; }
            set { myH = value;}
        }
    }

//No:2 接口的调用
    class Program
    {
        
        static void Main(string[] args)
        {
            MyPoint mp = new MyPoint(35, 170); //传入实际参数
            print(mp);
            Console.Read();
        }
        private static void print(Ipeople ip)
        {
            Console.WriteLine("体重为:{0},身高为:{1}\n", ip.w, ip.h);
        }
    }
}

No : 4结果如下,不知道你是否有所领悟呢。

 
 
其实我们写的代码都可以封装成接口以便以后使用时不会重复花更多时间做无用功。

posted on 2016-05-16 17:09  木乃伊人  阅读(5541)  评论(0编辑  收藏  举报

导航