C#委托

来源:互联网 发布:打击网络犯罪工作总结 编辑:程序博客网 时间:2024/06/07 18:36
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication2
{


    //委托:用来存放一个或多个方法的类型,相当于C++中的函数指针,
    //但是委托对方法的参数类型及个数和方法的返回类型是确定的


    delegate void DelWork();
    //一个能存放计算方法的委托
    delegate int DelCalulate(int i,int j);


    class President//总统
    {
        public void DoWork(DelWork d)
        {
            d();//若原方法无参数,这里无参数
        }
    }


    class Calculator
    { 
    public static  void  Calculate(DelCalulate dc,int a,int b)
    {
      int c=  dc(a, b);
      Console.WriteLine(c);
    }
    }




    class Program
    {


        public void Study()
        {
            Console.WriteLine("study...");
        }


        public int Sum(int a, int b)
        {
            return a + b;
        }


        public int Fun1(int a, int b)
        {
            return a - b;
        }
        static void Main(string[] args)
        {
            Program p=new Program();


            //委托最大的作用是用来将方法作为参数传递的
            //DelWork dw = new DelWork(p.Study);
            //President pd = new President();
            //pd.DoWork(dw);
            int i = 10;
            int j = 20;
            Calculator.Calculate(p.Sum, i, j);




           
        }
    }
}