接口

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

namespace 接口
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arr = new ArrayList();

            Ren r = new Ren();
            //r.chifan();
            //r.Skill();
            //r.Sport1();

            Random ran = new Random();

            arr.Add(r);
            arr.Add(ran);

            foreach (object o in arr)
            {
                Ren rr = o as Ren;
                if (rr != null)
                {
                    rr.chifan();
                }
                else
                {
                    Console.WriteLine("沒轉換成功!");
                }
            }

            Console.ReadKey();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 接口
{
    class Ren : HuoZhe, Work, Sports
    {
        public override void chifan()
        {
            Console.WriteLine("用嘴吃飯!");
        }

        public void Skill()
        {
            Console.WriteLine("會編程!");
        }

        public void Sport1()
        {
            Console.WriteLine("會踢足球!");
        }

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

namespace 接口
{
    abstract class HuoZhe
    {
        public abstract void chifan();

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

namespace 接口
{
    public interface Work  //接口數據 interface
    {
        void Skill();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 接口
{
    public interface Sports
    {
        void Sport1();
    }
}

接口:
在團隊開發中,一個類,須要多個模塊組合起來纔是完整的類;
多我的開發不一樣的模塊,最後要把它們拼接起來,靠的就是接口;編程

一個類,須要繼承多個類纔是完整的,可是程序規定,一個類只能繼承一個父類;
爲了解決這個問題,就出現了接口,一個類能夠繼承無數個接口;dom

人 這個類,須要會吃飯,技能,運動,纔是一個完整的人;
吃飯這個功能是A單獨開發的,做爲人的最基本的父類,使用的是抽象類;
技能和運動,是B和C分別開發的,須要人這個類來繼承,可是已經有父類了;
那麼B和C就使用的接口,來讓人這個類能夠繼承他們寫的兩個功能模塊;ide

接口裏面的方法很像抽象方法;spa

接口也是起到一個規範和約束的做用;code


is和as運算符:
is是判斷是不是某個類型,返回true或false
o as Ren; 若是轉換成功了,沒問題;
若是沒轉換成功,不會報出錯誤,而是返回一個null值blog

相關文章
相關標籤/搜索