首页 > 其他 > 详细

迭代委托链

时间:2015-01-12 16:18:21      阅读:311      评论:0      收藏:0      [点我收藏+]

有时候调用一个委托链需要获取委托链中每个调用的返回值,这是时候需要调用 system.Delegate类提供的GetInvocation方法去获取一组委托,实例如下:

 

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

namespace ConsoleApplication2
{
  public delegate double ProcessResults(double x,double y);

  public class Processor
  {
    public Processor(double factor)
    {
      this.factor=factor;

    }
    public double Compute(double x,double y)
    {
      double result=factor;
      Console.WriteLine("{0}",result);
      return result;
    }
    public static double StaticCompute(double x,double y)
    {
      double result=(x+y)*0.5;
      Console.WriteLine("{0}",result);
      return result;
    }

    private double factor;

  }


    class Program
    {

      static void Main(string[] args)
      {
        Processor proc1 = new Processor(0.2);
        Processor proc2 = new Processor(0.5);
        ProcessResults[] delegates = new ProcessResults[]{
          proc1.Compute,
          proc2.Compute,
          Processor.StaticCompute};
        ProcessResults chained = delegates[0] + delegates[1] + delegates[2];
        Delegate[] chain = chained.GetInvocationList();
        double accumulator = 0;
        for (int i = 0; i < chain.Length; i++)
         {

          ProcessResults current = (ProcessResults)chain[i];
          accumulator += current(4,5);

          }
          Console.WriteLine("Output:{0}",accumulator);
          Console.ReadKey();

          }
        }
      }

迭代委托链

原文:http://www.cnblogs.com/ZLGBloge/p/4218474.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!