首页 > 代码库 > 迭代委托链

迭代委托链

有时候调用一个委托链需要获取委托链中每个调用的返回值,这是时候需要调用 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();

          }
        }
      }

迭代委托链