委托笔记(1)-委托链接(多播委托)

没有返回结果的委托链接:

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

namespace Demo_Delegate
{
    class Program
    {
        delegate void MethodsDelegate();

        static void Main(string[] args)
        {
            // 首先对 methods 委托赋值,使其指向 Method1() ;
            // 接下来使用 += 运算将 Method2() 和 Method2() 添加到该委托;
            // 使用 -= 运算从委托中删除方法
            MethodsDelegate methods = Method1;
            methods += Method2;
            methods += Method3;

            // call the deletegate method(s)
            methods();
            Console.ReadKey();

        }
        static private void Method1()
        {
            Console.WriteLine("I am Method 1.");
        }

        static private void Method2()
        {
            Console.WriteLine("I am Method 2.");
        }

        static private void Method3()
        {
            Console.WriteLine("I am Method 3.");
        }
    }
}

  

输出的结果为:
         I am Method 1.

         I am Method 2.

         I am Method 3.

 

有返回结果的委托链接:

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

namespace Demo_Delegate2
{
    class Program
    {
        delegate int  MethodsDelegate(ref int num1, ref int num2);

        static void Main(string[] args)
        {
            int num1 = 0;
            int num2 = 0;

            MethodsDelegate methods = Method1;
            methods += Method2;
            methods += Method3;

            Console.WriteLine(methods(ref num1, ref num2));
            Console.WriteLine("num1: {0}  num2: {1}", num1, num2);
            Console.ReadKey();
        }

        static private int Method1(ref int num1, ref int num2)
        {
            Console.WriteLine("I am Method 1.");
            num1 = 1;
            num2 = 1;
            return 1;
        }

        static private int Method2(ref int num1, ref int num2)
        {
            Console.WriteLine("I am Method 2.");
            num1 = 2;
            num2 = 2;
            return 2;
        }

        static private int Method3(ref int num1, ref int num2)
        {
            Console.WriteLine("I am Method 3.");
            num1 = 3;
            num2 = 3;
            return 3;
        }
    }
}

  

输出的结果为:         

         I am Method 1.

         I am Method 2.

         I am Method 3.

         3

         num1:3       num2:3

posted on 2012-07-09 12:23  huobaby  阅读(111)  评论(0编辑  收藏  举报