日期:2014-05-18  浏览次数:20932 次

小白求教:大家看错在哪?
刚学委托,写了下面的一段代码:
C# code
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

------解决方案--------------------
使用多重委托要求返回值为void, 不然的话有多个返回,系统怎么知道你须要哪一个
------解决方案--------------------
你得改一下,向这养就可以了

delegate double MathsOp(double x);

class Program
{
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;
}
}

}

------解决方案--------------------
MathsOp operation = new MathsOp(Mydelegate.MultiplyBy2);//实例化
operation += new MathsOp(Mydelegate.AddBy2);
这两步产生了operation的多播代理,实际上你先后调用了MultiplyBy2和AddBy2(顺续并不一定)。
相当于下面两步
result = 1.23 * 2;
result = 1.23 + 2;
所以
输出结果: 
1.23 multiply by 2 is 3.23 

------解决方案--------------------
C# code
MathsOp operation = new MathsOp(Mydelegate.MultiplyBy2);//实例化
operation += new MathsOp(Mydelegate.AddBy2);

------解决方案--------------------
不过,用+=时你要清楚你再做什么。对于普通的委托,没有什么大碍。如果是事件,就有所不同了,被注册的回调都会响应的。
------解决方案--------------------
2楼的办法治标不治本,根据文档多播发生的顺序是不一定的(虽然看起来有序)。
根据楼主的需求应该不是要多播。
------解决方案--------------------
因为第一次显示的时候,委托连上有2个方法,所以它返回了链上最后的方法调用,然后你又把链上的方法去掉了一个,链上还有一个方法,所以,还是一样的