码迷,mamicode.com
首页 > 其他好文 > 详细

迭代委托链

时间:2015-01-12 16:20:00      阅读:138      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!