深入委托与多播委托的详解_C#教程

分享到:

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
    class 简单的委托实例
    {
        public static double Area(double Val)
        {
            return Val * 2;
        }
        public static double Scare(double Val)
        {
            return Val * Val;
        }
    }
    class Test
    {
        public delegate double delegateTest(double dd);
        static void Main()
        {
            //实例化了个委托数组,(一旦定义了委托类,就可以实例化它的实例)
            delegateTest[] Operations =
                {
                    //说明了委托的一种方式,把方法组合到数组
                  new delegateTest(简单的委托实例.Area),
                  new delegateTest(简单的委托实例.Scare)
                };
            for (int i = 0; i < Operations.Length; i++)
            {
                Console.WriteLine("Using Operations[{0}]", i);
                Test MyTest = new Test();
                //把委托传递给ProcessDelagate()这个方法,Operations[0]可以理解成delegateTest Operations =new delegateTest(简单的委托实例.Area);调用ProcessDelagate这个方法的时候Operations代理的方法是简单的委托实例.Area
                MyTest.ProcessDelagate(Operations[i], 12.0);
                MyTest.ProcessDelagate(Operations[i], 2.0);
                Console.WriteLine();
            }
        }
        //把委托作为一个参数传递到ProcessDelagate()第一个参数中
        void ProcessDelagate(delegateTest Action, double d)
        {
            double Result = Action(d);
            Console.WriteLine("提供的值是{0},结果是{1}", d, Result);
        }
    }
}


using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
    //如果要多次调用这个方法,那么就要多次调用这个委托,委托包含多个方法,这个种委托就是多播委托!
    class 多播委托
    {
        //用的是void没有返回值
        public delegate void DelageteTest(double val);
        static void Main()
        {
            //多播委托中添加2个方法
            DelageteTest MyTest = new DelageteTest(Test.Area);
            MyTest += new DelageteTest(Test.Scare);
            //下面的代码跟上面的3行代码是等价的
            //DelageteTest MyTest;
            //DelageteTest Test1 = new DelageteTest(Test.Area);
            //DelageteTest Test2 = new DelageteTest(Test.Scare);
            //MyTest = Test1 + Test2;
            多播委托 多 = new 多播委托();
            多.OPreation(MyTest, 2.0);
            多.OPreation(MyTest, 12.0);
        }
        void OPreation(DelageteTest Action, double d)
        {
            Action(d);
        }
    }
    class Test
    {
        public static void Area(double Val)
        {
            Console.WriteLine(Val * 2);
        }
        public static void Scare(double Val)
        {
            Console.WriteLine(Val * Val);
        }
    }
}

昵    称:
验证码:

相关文档: