1、委托
//声明委托
public delegate int MathDelegate(int value1,int value2);
class Program
{
static void Main(string[] args)
{
MathOpt myopt = new MathOpt();
Console.WriteLine( myopt.Add(2, 3));
//声明委托变量
MathDelegate oppDel;
//为委托变量赋值,委托变量与其代理的方法绑定
oppDel = myopt.Add;
//使用委托变量调用方法
Console.WriteLine(oppDel(2, 3));
}
}
class MathOpt
{
public int Add(int num1, int num2)
{
return num1 + num2;
}
}
2
//定义委托
public delegate int GenericFun(int a, int b);
static void Main(string[] args)
{
//声明委托变量
//GenericFun g = AddOpen;
//Console.WriteLine("作加法得:{0}",g(3, 5));
//g = SubOpen;
//Console.WriteLine("作减法得:{0}",g(3, 5));
Console.WriteLine("两个数相加得:{0}", PrintResult(AddOpen, 3, 5));
Console.WriteLine("两个数相减得:{0}", PrintResult(SubOpen, 3, 5));
}
3/
public delegate void Del(string testString);
class Program
{
static void Main(string[] args)
{
MessageTest Ok = new MessageTest();
Del d1 = new Del(Ok.Message1);
Del d2 = new Del(Ok.Message2);
Del d3 = new Del(Ok.Message3);
Del dAll = d1 + d2 + d3;
dAll("代理之广播!");
dAll = dAll - d3;
dAll("代理之多路委托!");
}
}
class MessageTest
{
public void Message1(string testString)
{
Console.WriteLine("使用Message1" + testString);
}
public void Message2(string testString)
{
Console.WriteLine("使用Message2" + testString);
}
public void Message3(string testString)
{
Console.WriteLine("使用Message3" + testString);
}
}
public static int AddOpen(int a, int b)
{
return a + b;
}
public static int SubOpen(int a, int b)
{
return a - b;
}
public static int PrintResult(GenericFun action, int a, int b)
{
int result = action(a, b);
return result;
}
委托与事件
class Program
{
static void Main(string[] args)
{
//委托的对象
Delegate objDelegate = new Delegate();
//实例化classA的对象
classA objclassA = new classA();
classB objclassB = new classB();
//订阅事件
objDelegate.NotifyEveryOne+=new Delegate.MeDelegate(objclassA.DisMethod);
objDelegate.NotifyEveryOne+=new Delegate.MeDelegate(objclassB.DisMethod);
objDelegate.Notify();
}
}
class classA
{
public void DisMethod()
{
Console.WriteLine("ClassA已接到NotifyEventOn事件的通知!");
}
}
public class classB
{
public void DisMethod()
{
Console.WriteLine("ClassB已接到NotifyEventOn事件的通知!");
}
}
class Delegate
{
//定义委托
public delegate void MeDelegate();
//定义事件
public event MeDelegate NotifyEveryOne;
public void Notify()
{
//如果事件不为null
if (NotifyEveryOne!=null)
{
Console.WriteLine("触发事件!");
//触发事件
NotifyEveryOne();
}
}
}