C# - 层分离 - 如何使用这些代理?

时间:2016-04-21 23:45:08

标签: c#

以下是相关代码:

ClickMeGame.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassLibrary
{
    public class ClickMeGame
{
    public OnClickMe onClickMeCallback;

    public int score;

    public ClickMeGame()
    {
        score = 0;
    }

    private void IncrementScore()
    {
        score++;
    }
}
}

ClickMeCallBackDefinitions.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassLibrary
{
    public delegate void OnClickMe();
}

MainWindow.cs (Windows窗体)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ClassLibrary;

namespace ClickMe
{
    public partial class mainWindow : Form
{
    private ClickMeGame game;

    public mainWindow()
    {
        InitializeComponent();

        game = new ClickMeGame();
        game.onClickMeCallback = clickMeButton_Click();

    }

    private void clickMeButton_Click(object sender, EventArgs e)
    {
        UpdateUI(); 
    }

    private void UpdateUI()
    {
        scoreLabel.Text = string.Format("The score is: {0}", game.score);
    }
}
}

所以我要做的是,当用户点击表单上的按钮时,我希望表单上的标签随游戏分数一起更新,每次点击都会增加。

我正在学习/希望能够与代表这样做,因为我想将项目分成两层;演讲和逻辑。我知道这样做是不必要的,但是我想这样做,当你点击按钮时,Windows窗体通过委托/回调方法接收有关游戏得分的信息。我不确定如何做到这一点,但我尝试制作回调定义并参考它,但我从那里迷失了。

1 个答案:

答案 0 :(得分:0)

假设UI按钮使用click事件clickMeButton_Click,那么你去吧。

public partial class mainWindow : Form
{
    private ClickMeGame game;

    public mainWindow()
    {
        InitializeComponent();

        game = new ClickMeGame();
        game.onClickMeCallback = param => UpdateUI();

    }

    private void clickMeButton_Click(object sender, EventArgs e)
    {
        game.onClickMeCallback.Invoke(); 
    }

    private void UpdateUI()
    {
        scoreLabel.Text = string.Format("The score is: {0}", game.score);
    }
}