有时候调用一个委托链需要获取委托链中每个调用的返回值,这是时候需要调用 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();
}
}
}
非绑定的委托
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ConsoleApplication2
{
delegate double ApplyRaiseDelegate(Employee emp, Decimal percent);
public class Employee
{
private decimal salary;
public decimal Salary
{
get { return salary; }
}
public Employee(decimal salary)
{
this.salary=salary;
}
public void ApplyRaiseOf(decimal percent)
{
salary *= (1+ percent);
}
}
class Program
{
static void Main(string[] args)
{
List<Employee> employees = new List<Employee>();
employees.Add(new Employee(4000));
employees.Add(new Employee(5000));
employees.Add(new Employee(6000));
MethodInfo mi = typeof(Employee).GetMethod("ApplyRaiseOf", BindingFlags.Public | BindingFlags.Instance);
ApplyRaiseDelegate applyRais = (ApplyRaiseDelegate)Delegate.CreateDelegate(typeof(ApplyRaiseDelegate), mi);
foreach (Employee e in employees)
{
applyRais(e,(decimal)0.1);
Console.WriteLine(e.Salary);
}
Console.ReadKey();
}
}
}