委托及多路广播委托

来源:互联网 发布:it工作经历 编辑:程序博客网 时间:2024/05/04 11:49
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace delegate1{    public delegate int Transformer(int x);    public class Util    {        public static void Transform(int[] value, Transformer t)        {            for (int i = 0; i < value.Length; i++)            {                value[i] = t(value[i]);            }        }    }    class Program    {        static int Square(int x) { System.Console.WriteLine("once" + x); return x * x; }        static void Main(string[] args)        {            int[] value = new int[3] { 1, 2, 3 };            Transformer t = Square;            t += Square;            Util.Transform(value, t);            foreach (int item in value)                System.Console.WriteLine(item);        }    }}

输出:

once1
once1
once2
once2
once3
once3
1
4
9

说明 都调用完毕之后才返回的,参数不回发生变化。如若改为引用类型:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace delegate1{    public delegate void Transformer(ref int x);    public class Util    {        public static void Transform(int[] value, Transformer t)        {            for (int i = 0; i < value.Length; i++)            {                t(ref value[i]);            }        }    }    class Program    {        static void Square(ref int x) { System.Console.WriteLine("once" + x); x = x * x; }        static void Main(string[] args)        {            int[] value = new int[3] { 1, 2, 3 };            Transformer t = Square;            t += Square;            Util.Transform(value, t);            foreach (int item in value)                System.Console.WriteLine(item);        }    }}

返回:

once1
once1
once2
once4
once3
once9
1
16
81

原创粉丝点击