6.10委托

概念:
1.委托类似于C++函数指针,但是他是类型安全的.
2.委托允许将方法作为参数进行传递
 
 
例:
 
namespace ConsoleApplication1
{
    delegate int mydelegate(int x,int y); //委托声明
    class MyDelegate
    {
        public int add(int x, int y)
        {
            return x + y;
        }

        public int sub(int x, int y)
        {
            return x - y;
        }
    }
    class program1
    {
        public static void Main(string[] args)
        {
            MyDelegate p = new MyDelegate();
            
            mydelegate pAdd = new mydelegate(p.add);//委托实例化
            mydelegate pSub = new mydelegate(p.sub);
            
            Console.WriteLine("9+1={0}", pAdd(9, 1));//委托调用
            Console.WriteLine("9-1={0}", pSub(9, 1));
            
            Console.ReadLine();
        }


    }
}

 

封装多个方法:

MyDelegate p = new MyDelegate();
mydelegate a,b;

b=p.add;
a=b; //将add方法添加到调用列表中

b=p.sub;
a+=b; //将sub方法添加到调用列表中

p(9,1);

 

匿名方法:

 delegate void mydelegate1(int x,int y);
    class Class1
    { 
        public static void Main(string[] args)
        {
            mydelegate1 p = delegate(int x,int y)
          {
             Console.WriteLine("result={0}", x+y);
             Console.ReadLine();
          };    //注意
            
          p(9,1);
        }


    }

 



posted on 2013-01-15 17:07  msony210  阅读(85)  评论(0)    收藏  举报

导航