匿名函数/委托?

时间:2012-08-19 21:50:48

标签: c# delegates c++-cli anonymous-function

我正在将我的C#Windows应用程序转换为C ++ \ CLI应用程序。

我坚持'转换'这段代码:

void LoadWindow(Mode mode) {
        if (timer != null && timer.Enabled) return;

        int currentIndex = Windows.IndexOf(panel.Controls[0]);
        int loadInex = 0, exitLeft = 0, entranceLeft = 0, stopLeft = 0;

        if (mode == Mode.Next)
        {
            loadInex = currentIndex == Windows.Count - 1 ? 0 : ++currentIndex;
            exitLeft = -((panel.Width / 2 - Windows[currentIndex].Width / 2) + Windows[currentIndex].Width);
            entranceLeft = panel.Width;
        }
        else
        {
            loadInex = currentIndex == 0 ? Windows.Count - 1 : --currentIndex;
            exitLeft = panel.Width;
            entranceLeft = -panel.Width;
        }

        stopLeft = panel.Width / 2 - Windows[loadInex].Width / 2;

        Windows[loadInex].Left = entranceLeft;
        panel.Controls.Add(Windows[loadInex]);

        timer = new System.Windows.Forms.Timer();
        timer.Interval = 10;
        timer.Tick += new EventHandler(delegate(object sender, EventArgs e) {
            if (mode == Mode.Next)
            {
                if (exitLeft <= panel.Controls[0].Left)
                    panel.Controls[0].Left -= 50;

                if (stopLeft <= panel.Controls[1].Left)
                    panel.Controls[1].Left = panel.Controls[1].Left - 50 < stopLeft ? stopLeft : panel.Controls[1].Left - 50;

                if (exitLeft >= panel.Controls[0].Left && stopLeft >= panel.Controls[1].Left)
                {
                    panel.Controls.RemoveAt(0);
                    timer.Enabled = false;
                }
            }

            if (mode == Mode.Previous)
            {
                if (exitLeft >= panel.Controls[0].Left)
                    panel.Controls[0].Left += 50;

                if (stopLeft >= panel.Controls[1].Left)
                    panel.Controls[1].Left = panel.Controls[1].Left + 50 > stopLeft ? stopLeft : panel.Controls[1].Left + 50;

                if (exitLeft <= panel.Controls[0].Left && stopLeft <= panel.Controls[1].Left)
                {
                    panel.Controls.RemoveAt(0);
                    timer.Enabled = false;
                }
            }
        });

        timer.Enabled = true;
    }

AFAIK C ++ \ CLI不支持匿名方法(我甚至不能利用lambdas)。

如果EventHandler委托在LoadWindow函数中没有使用局部变量,那么这不会有问题。

我该如何实现?我考虑使用一个简单的仿函数类,但是有更“优雅”的方法吗?

谢谢, 亚历

0 个答案:

没有答案