天天看點

C#學習之路抽象類和委托

抽象類(abstract)

抽象類不能執行個體化,類是一個模闆,抽象類就是半個模闆。當我們繼承抽象類的時候必須實作抽象函數的方法

God.cs

abstract class God
    {
        public abstract void Fly();
    }
           

Human.cs//繼承抽象類必須實作抽象函數的方法

class Human:God
    {
        public override void Fly()
        {
            Console.WriteLine("神會飛");
        }
    }
           

委托

C#中的委托(delegate)類似于C或C++中函數的指針,委托對象必須使用 new 關鍵字來建立,且與一個特定的方法有關。委托特别用于實作事件和回調方法。

Program.cs

Human human = new Human();//子類構造函數,調用重寫方法
            human.Fly();
//也可以這樣,父類(God)聲明一個神,使用子類(Human)執行個體化
God god = new Human();

            god.Fly();

//委托可以把方法當做參數來傳遞
private delegate string Get(); //定義一個委托
static void Main(string[] args)
{
    int x=40;
    //1.
    Get get=new Get(x.ToString);//委托當成參數
    string a=get();//可以和方法一樣直接使用
    //2.Get a=x.ToString;
}


private delegate void PrintString();//聲明一個委托類型
        static void PrintStr(PrintString print)//傳遞一個委托類型的參數
        {
            print();
        }
        static void Method1()
        {
            Console.WriteLine("Method1");
        }
        static void Method2()
        {
            Console.WriteLine("Method2");
        }
static void Main(string[] args)
{
            PrintString method = Method1;//委托類型也必須要初始化才能使用
            PrintStr(method);
            method = Method2;
            PrintStr(method);
}
           

Action委托:系統内置(預定義)的一個委托類型,他可以指向一個沒有傳回值沒有參數的方法 

Func委托: 可以傳入參數,必須有傳回值 

委托的多點傳播(Multicasting of a Delegate)

“+” 運算符:可以進行合并委托對象,一個合并委托調用它所合并的兩個委托。

“-”  運算符:用于從合并的委托中移除元件委托。

當建立一個委托被調用時要調用的方法的調用清單時稱為委托的多點傳播,又名多點傳播。舉例來說就是本來分開運算的兩個對象,合并到一起,同時進行運算。

delegate int NumberChanger(int n);
namespace DelegateAppl
{
    class TestDelegate
    {
        static int num = 10;
        public static int AddNum(int p)
        {
            num += p;
            return num;
        }
        public static int MultNum(int q)
        {
            num *= q;
            return num;
        }
        public static int getNum()
        {
            return num;
        }
        static void Main(string[] args)
        {
            NumberChanger nc;
            NumberChanger nc1 = new NumberChanger(AddNum);
            NumberChanger nc2 = new NumberChanger(MultNum);
            nc = nc1;
            nc += nc2;
            nc(5);
            Console.WriteLine("Value of Num:{0}", getNum());
            Console.ReadKey();
        }
    }
}
//The result of program is : 75  
//This program is equivalent to adding and then multiplying 
           

委托的具體用途

using System;
using System.IO;
namespace DelegateAppl
{
    class PrintString
    {
        static FileStream fs;
        static StreamWriter sw;
        //委托聲明
        public delegate void printString(string s);
        //讀方法列印到控制台
        public static void WriteToSceen(string str)
        {
            Console.WriteLine("The String is :{0}", str);
        }
        //該方法列印到檔案
        public static void WriteToFile(string s)
        {
            fs = new FileStream("c:\\message.txt",
                FileMode.Append, FileAccess.Write);
            sw = new StreamWriter(fs);
            sw.WriteLine(s);
            sw.Flush();
            sw.Close();
            fs.Close();
        }
        //該方法把委托作為參數,并使用它調用方法
        public static void sendString(printString ps)
        {
            ps("Hello World");
        }
        static void Main(string[] args)
        {
            printString ps1 = new printString(WriteToSceen);
            printString ps2 = new printString(WriteToFile);
            sendString(ps1);
            sendString(ps2);
            Console.ReadKey();
        }
    }
}
           

以上代碼執行結果:Hello World

借用菜鳥教程的一個例子,很好的了解委托多點傳播的原理

public class MrZhang
{
    public static void BuyTicket()
    {
        Console.WriteLine("MrZhang BuyTicket");
    }
    public static void BuyMovieTicket()
    {
        Console.WriteLine("MrZhang BuyMovieTicket");
    }
}
class MrMing
{
    public delegate void BuyTicketEventHandler();   //Declare a delegate,it's a command.
    public static void Main(string[] args)
    {
        BuyTicketEventHandler myDelegate = new BuyTicketEventHandler(MrZhang.BuyTicket);
        myDelegate += MrZhang.BuyMovieTicket;   //At this point the delegate is attached to the specify method
        myDelegate();
        Console.ReadKey();
    }
}
//This program result is:
//MrZhang BuyTicket
//MrZhang BuyMovieTicket