c#-委托

来源:互联网 发布:php文件上传大小限制 编辑:程序博客网 时间:2024/05/16 23:45
c#委托
委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法,可以避免在程序中大量使用If-Else(Switch)语句,同时使得程序具有更好的可扩展性。
委托就是相当于c++中的指针。
总的来说委托就是方法里面还有方法!

步骤:1.定义一个委托,类型和参数;
            2.用于委托的方法,类型和参数与委托保持一致;
            3.调用委托;
实例一:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace delegateDemo
{
    public delegate void callDelegate(int a, int b);


    class Program
    {
        //定义一个委托
       


        private static void big(int a, int b)
        {
            if (a > b)
                Console.WriteLine("a"+a);
            else
                Console.WriteLine("a"+b);
        }


        private static void small(int a, int b)
        {
            if (a < b)
                Console.WriteLine(a);
            else
                Console.WriteLine(b);
        }


        //在函数内使用委托
        private static void Process(int a, int b, callDelegate call)
        {
            call(a, b);
        }
        static void Main(string[] args)
        {
            //委托实例与方法相关联
            Process(10, 20,big);
            Process(10, 20,small);
            Console.ReadKey();
            
        }
    }
}

实例二:

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

namespace delegateDemo
{
    public class ab
    {
        //用于委托调用的方法
        public int Big(int a, int b)
        {
            if (a > b)
                return a;
            else
                return b;
        }
        public int Small(int a, int b)
        {
            if (a < b)
                return a;
            else
                return b;
        }
    }
    class Program
    {
        //定义一个委托
        public delegate int callDelegate( int a, int b);

        //在函数内使用委托
        public static int Process( int a, int b, callDelegate call)
        {
            return call(a, b);
        }
        static void Main(string[] args)
        {
            //委托实例与方法相关联
             callDelegate delegateBig=new callDelegate( new ab().Big);
             int big = delegateBig(10, 20);

            //用委托调用相关联的方法
             int small = Process(10, 20, new callDelegate( new ab ().Small));
             Console.WriteLine(big);
             Console.WriteLine(small);
        }
    }
}


0 0
原创粉丝点击