using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Simple delegate instance
{
public static double Area(double Val)
{
return Val * 2;
}
public static double Scare(double Val)
{
return Val * Val;
}
}
class Test
{
public delegate double delegateTest(double dd);
static void Main()
{
// Instantiate a delegate array , ( 1 Defines the delegate class , I can instantiate it.)
delegateTest[] Operations =
{
// It says what the delegate is 1 Kind of way , Combine methods into an array
new delegateTest( Simple delegate instance .Area),
new delegateTest( Simple delegate instance .Scare)
};
for (int i = 0; i < Operations.Length; i++)
{
Console.WriteLine("Using Operations[{0}]", i);
Test MyTest = new Test();
// Pass the delegate to ProcessDelagate() This method ,Operations[0] Can be interpreted as delegateTest Operations =new delegateTest( Simple delegate instance .Area); call ProcessDelagate This way Operations The proxy method is a simple delegate instance .Area
MyTest.ProcessDelagate(Operations[i], 12.0);
MyTest.ProcessDelagate(Operations[i], 2.0);
Console.WriteLine();
}
}
// Delegate as 1 Two parameters are passed to ProcessDelagate() The first 1 In the parameters
void ProcessDelagate(delegateTest Action, double d)
{
double Result = Action(d);
Console.WriteLine(" The value provided is {0}, As a result, {1}", d, Result);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
// If you want to call this method multiple times , So you're going to call this delegate multiple times , A delegate contains multiple methods , This kind of delegation is multicast delegation!
class The multicast delegate
{
// Using a void No return value
public delegate void DelageteTest(double val);
static void Main()
{
// Added in multicast delegate 2 A method of
DelageteTest MyTest = new DelageteTest(Test.Area);
MyTest += new DelageteTest(Test.Scare);
// The following code follows 3 Lines of code are equivalent
//DelageteTest MyTest;
//DelageteTest Test1 = new DelageteTest(Test.Area);
//DelageteTest Test2 = new DelageteTest(Test.Scare);
//MyTest = Test1 + Test2;
The multicast delegate more = new The multicast delegate ();
more .OPreation(MyTest, 2.0);
more .OPreation(MyTest, 12.0);
}
void OPreation(DelageteTest Action, double d)
{
Action(d);
}
}
class Test
{
public static void Area(double Val)
{
Console.WriteLine(Val * 2);
}
public static void Scare(double Val)
{
Console.WriteLine(Val * Val);
}
}
}