刚学委托,写了下面的一段代码:
namespace Pra_Delegate3
{
delegate double MathsOp(double x); //定义一个委托
class Program
{
static void Main(string[] args)
{
//Mydelegate myDelegate = new Mydelegate(); MathsOp operation = new MathsOp(Mydelegate.MultiplyBy2);//实例化
operation += new MathsOp(Mydelegate.AddBy2);
double x = 1.23;
double result = operation(x);
Console.WriteLine("{0} multiply by 2 is {1}",x,result);
operation -= new MathsOp(Mydelegate.MultiplyBy2);
Console.WriteLine("{0} add by 2 is {1}",x,result);
Console.Read();
} public class Mydelegate
{
public static double MultiplyBy2(double x)
{
return x * 2;
} public static double AddBy2(double x)
{
return x + 2;
}
}
}
}
输出结果:
1.23 multiply by 2 is 3.23
1.23 add by 2 is 3.23
namespace Pra_Delegate3
{
delegate double MathsOp(double x); //定义一个委托
class Program
{
static void Main(string[] args)
{
//Mydelegate myDelegate = new Mydelegate(); MathsOp operation = new MathsOp(Mydelegate.MultiplyBy2);//实例化
operation += new MathsOp(Mydelegate.AddBy2);
double x = 1.23;
double result = operation(x);
Console.WriteLine("{0} multiply by 2 is {1}",x,result);
operation -= new MathsOp(Mydelegate.MultiplyBy2);
Console.WriteLine("{0} add by 2 is {1}",x,result);
Console.Read();
} public class Mydelegate
{
public static double MultiplyBy2(double x)
{
return x * 2;
} public static double AddBy2(double x)
{
return x + 2;
}
}
}
}
输出结果:
1.23 multiply by 2 is 3.23
1.23 add by 2 is 3.23
{
static void Main(string[] args)
{
MathsOp operation = new MathsOp(Mydelegate.MultiplyBy2);
operation += new MathsOp(Mydelegate.AddBy2);
double x = 1.23;
double result = operation(x);
Console.WriteLine("{0} Add by 2 is {1}", x, result);
operation -= new MathsOp(Mydelegate.AddBy2);
result = operation(x);
Console.WriteLine("{0} Multiply by 2 is {1}", x, result);
Console.Read();
} public class Mydelegate
{
public static double MultiplyBy2(double x)
{
return x * 2;
} public static double AddBy2(double x)
{
return x + 2;
}
}}
operation += new MathsOp(Mydelegate.AddBy2);
这两步产生了operation的多播代理,实际上你先后调用了MultiplyBy2和AddBy2(顺续并不一定)。
相当于下面两步
result = 1.23 * 2;
result = 1.23 + 2;
所以
输出结果:
1.23 multiply by 2 is 3.23
operation += new MathsOp(Mydelegate.AddBy2);这样实际上是指定了两个回调方法,这两个方法先后执行,返回值是后一个方法的。这样可以看得更清楚: public static double MultiplyBy2(double x)
{
Console.WriteLine("x * 2 = " + x * 2);
return x * 2;
}
还有就是,为什么说两个方法执行的顺序不一样呢?
operation += new MathsOp(Mydelegate.AddBy2)不是把添加入队列,
而队列就是先进先出啊?
另外,你这是在考察multicast delegate的性质吧?不然的话,六楼那位说的很对。实际中,你不可依赖这种特性。应为这种顺序
的规定(便利链表的顺序)没有被写到requirement specification中去。微软并不保证这种调用的有序性.微软的一位员工曾在msdn
中说过这件事。