实例1:【基础使用】
using System;
namespace ConsoleApp1
{
class Program
{
delegate void MyDel(int value);
void PrintLow(int value)
{
Console.WriteLine("{0}-Low Value", value);
}
void PrintHigh(int value)
{
Console.WriteLine("{0}-High Value", value);
}
static void Main(string[] args)
{
Program program = new Program();
MyDel myDel;
Random rand = new Random();
int randomValue = rand.Next(99);
if (randomValue < 50)
{
myDel = program.PrintLow;
}
else
{
myDel = program.PrintHigh;
}
myDel(randomValue);
Console.ReadLine();
}
}
}
运行结果:
实例2:【为委托添加方法】
using System;
namespace ConsoleApp2
{
class Program
{
delegate void PrintFunction();
class Test
{
public void Print1()
{
Console.WriteLine("Print1--instance");
}
public static void Print2()
{
Console.WriteLine("Print2--static");
}
}
static void Main(string[] args)
{
Test t = new Test();
PrintFunction pf;
pf = t.Print1;
pf += Test.Print2;
pf += t.Print1;
pf += Test.Print2;
if (null != pf)
pf();
else
Console.WriteLine("Delegate is Empty");
Console.ReadLine();
}
}
}
运行结果:
实例3:【调用带返回值的委托】
using System;
namespace ConsoleApp3
{
delegate int MyDel();
class MyClass
{
int IntValue = 5;
public int Add2()
{
IntValue += 2;
return IntValue;
}
public int Add3()
{
IntValue += 3;
return IntValue;
}
}
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
MyDel mDel = mc.Add2;
mDel += mc.Add3;
mDel += mc.Add2;
Console.WriteLine("Value:{0}", mDel());
Console.ReadLine();
Console.ReadLine();
}
}
}
运行结果:
实例4:【调用带引用参数的委托】
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
delegate void MyDel(ref int y);
class MyClass
{
public void Add2(ref int y) { y += 2; }
public void Add3(ref int y) { y += 3; }
}
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
MyDel mDel = mc.Add2;
mDel += mc.Add3;
mDel += mc.Add2;
int x = 8;
mDel(ref x);
Console.WriteLine("Value:{0}", x);
Console.ReadLine();
Console.ReadLine();
}
}
}
运行结果:
实例5:【匿名方法(anonymous method)】
using System;
namespace ConsoleApp5
{
delegate int OtherDel(int param);
class Program
{
static void Main(string[] args)
{
OtherDel del = delegate (int x)
{
return x + 20;
};
Console.WriteLine("{0}", del(5));
Console.WriteLine("{0}", del(8));
Console.ReadLine();
Console.ReadLine();
}
}
}
运行结果:
实例6:【Lambada表达式(无名函数)】
using System;
namespace ConsoleApp6
{
delegate double MyDel(int par);
class Program
{
static void Main(string[] args)
{
MyDel del = delegate (int x) { return x + 1; };
MyDel le1 = (int x) => { return x + 1; };
MyDel le2 = (x) => { return x + 2; };
MyDel le3 = x => { return x + 3; };
MyDel le4 = x => x + 4;
Console.WriteLine("{0}", del(12));
Console.WriteLine("{0}", le1(12));
Console.WriteLine("{0}", le2(12));
Console.WriteLine("{0}", le3(12));
Console.WriteLine("{0}", le4(12));
Console.ReadLine();
Console.ReadLine();
}
}
}
运行结果: