多播委托是具有对多个功能的引用的委托。当您调用多播委托时,该委托指向的所有功能都将被调用。
类型1:
0参数和void返回类型委托-
方法1-
using System;
delegate void SampleDelegate ();
class MainClass
{
public static void Main ()
{
SampleDelegate Del1 = new SampleDelegate (Message1);
SampleDelegate Del2 = new SampleDelegate (Message2);
SampleDelegate Del3 = new SampleDelegate (Message3);
SampleDelegate Del4 = Del1 + Del2 + Del3;
Del4 ();
}
Del4 - Del1;
Del4();
Del4 + Del1;
Del4();
public static void Message1 ()
{
Console.WriteLine ("This is message 1");
}
public static void Message2 ()
{
Console.WriteLine ("This is message 2");
}
public static void Message3 ()
{
Console.WriteLine ("This is message 3");
}
}
方法2 -
using System;
delegate void SampleDelegate ();
class MainClass
{
public static void Main ()
{
SampleDelegate del = new SampleDelegate (Message1);
del += Message2;
del += Message3;
del ();
del -= Message1;
del ();
del += Message4;
del ();
}
public static void Message1 ()
{
Console.WriteLine ("This is Message1");
}
public static void Message2 ()
{
Console.WriteLine ("This is Message2");
}
public static void Message3 ()
{
Console.WriteLine ("This is Message3");
}
public static void Message4 ()
{
Console.WriteLine ("This is Message4");
}
}
类型2:
0参数和int返回类型委托
方法1-
using System;
delegate int SampleDelagate ();
class MainClass
{
public static void Main ()
{
SampleDelagate del1 = new SampleDelagate (Method1);
SampleDelagate del2 = new SampleDelagate (Method2);
SampleDelagate del3 = new SampleDelagate (Method3);
SampleDelagate del4 = del1 + del2 + del3;
int ValueReturned = del4 ();
Console.WriteLine (ValueReturned);
}
public static int Method1 ()
{
return 1;
}
public static int Method2 ()
{
return 2;
}
public static int Method3 ()
{
return 3;
}
}
方法2-
与类型1相同的过程
因此,当存在MultiCast委托的返回类型时,返回值就是最后一个委托的返回值。
类型3:
int,int,ref int参数和void返回类型委托-
using System;
delegate void SampleDelegate (ref int SampleReferenceParameter);
class MainClass
{
public static void Main ()
{
SampleDelegate del1, del2, del3, del4;
del1 = new SampleDelegate (SampleMethodOne);
del2 = new SampleDelegate (SampleMethodTwo);
del3 = new SampleDelegate (SampleMethodTwo);
del4 = del1 + del2 + del3 - del3;
int SampleReferenceParameterValue = 0;
del4 (ref SampleReferenceParameterValue);
Console.WriteLine (SampleReferenceParameterValue);
}
public static void SampleMethodOne (ref int SampleReferenceParameter)
{
SampleReferenceParameter = 1;
}
public static void SampleMethodTwo (ref int SampleReferenceParameter)
{
SampleReferenceParameter = 2;
}
public static void SampleMethodThree (ref int SampleReferenceParameter)
{
SampleReferenceParameter = 3;
}
}