您的位置:首页 > 编程语言 > C#

c#-委托

2015-07-07 18:01 375 查看
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);         }     } }


阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: