chained delegate
In this chapter you will learn:
Chained Delegate
using System;/*from ja v a 2 s. c o m*/
public delegate double ComputeDelegate( double x,double y );
public class MyClass
{
public MyClass( ) {
}
public double Add( double x, double y ) {
double result = x+y;
Console.WriteLine( "InstanceResults: {0}", result );
return result;
}
public static double Subtract( double x,double y ) {
double result = x - y;
Console.WriteLine( "StaticResult: {0}", result );
return result;
}
private double factor;
}
public class MainClass
{
static void Main() {
MyClass proc1 = new MyClass( );
MyClass proc2 = new MyClass( );
ComputeDelegate[] delegates = new ComputeDelegate[] {
new ComputeDelegate( proc1.Add ),
new ComputeDelegate( proc2.Add ),
new ComputeDelegate( MyClass.Subtract )
};
ComputeDelegate chained = (ComputeDelegate) Delegate.Combine( delegates );
double combined = chained( 4, 5 );
Console.WriteLine( "Output: {0}", combined );
}
}
The code above generates the following result.
Get Invocation List
using System;//from j av a 2 s .c om
public delegate int IncrementDelegate(ref short refCount);
public class Factorial {
public static void Main() {
IncrementDelegate[] values = { Incrementer, Incrementer,Incrementer, Incrementer, Incrementer};
IncrementDelegate del = (IncrementDelegate)IncrementDelegate.Combine(values);
long result = 1;
short count = 1;
foreach (IncrementDelegate number in del.GetInvocationList()) {
result = result * number(ref count);
}
Console.WriteLine("{0} factorial is {1}", del.GetInvocationList().Length, result);
}
public static int Incrementer(ref short refCount) {
return refCount++;
}
}
Next chapter...
What you will learn in the next chapter:
- Define an anonymous method with the delegate keyword
- for loop in an anonymous delegate
- Anonymous delegate with parameter
Home » C# Tutorial » delegate, lambda, event