c# 委託

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//委託是一種安全地封裝方法的類型,它與 C 和 C++ 中的函數指針類似
namespace delegateExample
{
    delegate int Math(int x,int y);// 聲明一個委託
    delegate void MathMulti(int x,int y);// 多路委託返回要爲void 
    class ADD_SUB
    {
        public int Add(int x, int y)
        {
            return x + y;
        }
        public int Sub(int x, int y)
        {
            return x - y;
        }
    }
    class MUL_DIV
    {
        static public void Mul(int x, int y)// 可以委託靜態與非靜態的方法
        {
            Console.WriteLine("x*y is {0}",x*y);
        }
        static public void Div(int x, int y)
        {
            Console.WriteLine("x/y is {0}", x / y);
        }
    }
    class DeleParam//委託類型派生自 .NET Framework 中的 Delegate 類 當然可以做參數 
    {
        public static void MethodWithCallback(int param1, int param2, MathMulti callback)
        {
            callback(param1 , param2);
        }
    }
    //協變和逆變會提供用於使委託類型與方法簽名匹配的靈活性
    class Animal { }
    class Fish : Animal { };

    class Program
    {
        public delegate Animal AnimalMethod();//關於協變 協變允許方法具有的派生返回類型比委託中定義的更多
        public static Fish FishMethod() 
        {
            Console.WriteLine("FishMethod");
            return null;
        }

        private void MultiHandler(object sender, System.EventArgs e)//逆變 將委託與具有某個類型的參數的方法一起使用,這些參數是委託簽名參數類型的基類型
        {
            Console.WriteLine(e.ToString());
        }

        static void Main(string[] args)
        {
            ADD_SUB addsub = new ADD_SUB();
            
            Math math1 = new Math(addsub.Add);
            Console.WriteLine("{0}",math1(1,2));//3
            
            MathMulti math2 = new MathMulti(MUL_DIV.Mul);
            math2(1, 3);//is 3

            math2+= new MathMulti(MUL_DIV.Div);// math2 現在有兩種方法被調用
            math2(1,4);// is 4        is 0

            math2-= new MathMulti(MUL_DIV.Div);// math2 現在只有乘法方法被調用
            math2(1, 5);// is 5 

            DeleParam.MethodWithCallback(6, 1, MUL_DIV.Mul);// is 6 

            AnimalMethod am = FishMethod;
            am();

            

            Console.ReadLine();
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章