private void Draw(Action a)
        {
            g.FillRectangle(backgroundBrush, left, top, SIZE, SIZE);
            a();
            g.FillRectangle(Brushes.SkyBlue, left, top, SIZE, SIZE);
        }        public void Up()
        {
            Draw(() => { top -= SIZE; });
        }
如果反复调用Up(),是不是反复创建Action委托?

解决方案 »

  1.   

    这个例子当中,跟你参数是不是Action委托没有关系,a是方法内局部变量,没调用一次Draw,就创建一次这个局部变量
      

  2.   

    局部变量要创建我当然是知道的。
    a每次都指向top -= SIZE;这句话。那top -= SIZE;是每次up都临时创建,用后销毁;还是始终存在,只是创建a时都把它指向top -= SIZE;?
      

  3.   

    换个方式问:
    以下代码跟主贴代码哪个更好?        Action upAction;        public Block(Graphics g, int left, int top)
            {
                this.g = g;
                backgroundBrush = new SolidBrush(System.Drawing.SystemColors.Control);
                this.left = left;
                this.top = top;            upAction= () => { top -= SIZE; };
            }        private void Draw(Action a)
            {
                g.FillRectangle(backgroundBrush, left, top, SIZE, SIZE);
                a();
                g.FillRectangle(Brushes.SkyBlue, left, top, SIZE, SIZE);
            }        public void Up()
            {
                Draw(upAction);
            }
      

  4.   

    效果是一样的。匿名方法实际上也是作为一个方法被实现创建好放在内存中的。但的确每次你顶楼的方法都要new一个Action对象。3楼的效果和顶楼效果一样。