C# delegate

时间:2023-03-08 22:09:17
C# delegate

1. delegate

example1

class Program
{
public delegate int MyDelegate(int i); int MyFunc(int i)
{
return i;
} public void Foo()
{
MyDelegate f = MyFunc; Console.WriteLine(f());
Console.ReadKey();
}
}

example 2

// declare the delegate type
public delegate string MyDelegate(int arg1, int arg2); class Program
{
// INSERT DELEGATES HERE
static string func1(int a, int b)
{
return (a + b).ToString();
}
static string func2(int a, int b)
{
return (a * b).ToString();
} static void Main(string[] args)
{
MyDelegate f = func1;
Console.WriteLine("The number is: " + f(, ));
f = func2;
Console.WriteLine("The number is: " + f(, )); Console.WriteLine("\nPress Enter Key to Continue...");
Console.ReadLine();
}
}

2. anonymous delegate

 public delegate string MyDelegate(int arg1, int arg2);

    class Program
{
static void Main(string[] args)
{
// SNIPPET GOES HERE
MyDelegate f = delegate(int arg1, int arg2)
{
return (arg1 + arg2).ToString();
};
Console.WriteLine("The number is: " + f(, ));
// Keep the console window open until a key is pressed
Console.WriteLine("\nPress Enter Key to Continue...");
Console.ReadLine();
}
}

3. composable delegate (call multiple delegates with one function call)

 // declare the delegate type
public delegate void MyDelegate(int arg1, int arg2); class Program
{
static void func1(int arg1, int arg2)
{
string result = (arg1 + arg2).ToString();
Console.WriteLine("The number is: " + result);
}
static void func2(int arg1, int arg2)
{
string result = (arg1 * arg2).ToString();
Console.WriteLine("The number is: " + result);
}
static void Main(string[] args)
{
MyDelegate f1 = func1;
MyDelegate f2 = func2;
MyDelegate f1f2 = f1 + f2; // call each delegate and then the chain
Console.WriteLine("Calling the first delegate");
f1(, );
Console.WriteLine("Calling the second delegate");
f2(, );
Console.WriteLine("\nCalling the chained delegates");
f1f2(, ); // subtract off one of the delegates
Console.WriteLine("\nCalling the unchained delegates");
f1f2 -= f1;
f1f2(, ); Console.WriteLine("\nPress Enter Key to Continue...");
Console.ReadLine();
}
}