C#委托多播

时间:2016-06-04 13:35:58   收藏:0   阅读:171
 class Program
    {

        static void Main(string[] args)
        {
           
            Action<double> ops = MathOperations.Mutiply;

            ops += MathOperations.Squre;

            ops.Invoke(3);

        }

      
    }
 public class MathOperations
    {
        public static void Mutiply(double value)
        {
            Console.WriteLine("result:{0}", value * 2);
        }

        public static void Squre(double value)
        {
            Console.WriteLine("result:{0}", Math.Pow(value, 2));
        }
    }

 改进的调用方式,防止多播中的末一个发生异常

 

 class Program
    {

        static void Main(string[] args)
        {
           
            Action<double> ops = MathOperations.Mutiply;

            ops += MathOperations.Squre;

            //ops.Invoke(3);

            Delegate[] delegates = ops.GetInvocationList();

            foreach (Action<double> d in delegates)
            {
                try
                {
                    d(3);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            }
        }

      
    }

 

原文:http://www.cnblogs.com/weiweictgu/p/5558626.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!