C#Windows窗体应用程序:从业务逻辑中分离GUI

Hap*_*cky 9 c# events user-interface business-logic

我想就如何在简单的C#Windows窗体应用程序中分离UI和业务逻辑提出一些建议.

我们来看这个例子:

UI由简单的文本框和按钮组成.用户输入0到9之间的数字并单击该按钮.程序应该为数字添加10并使用该值更新文本框.

在此输入图像描述

业务逻辑部分应该不知道UI.如何实现这一目标?

这是空的Process类(业务逻辑):

namespace addTen
{
    class Process
    {
        public int AddTen(int num)
        {
            return num + 10;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要求是:

  1. 当用户单击该按钮时,会以某种方式调用Process :: AddTen.
  2. 必须使用Process :: AddTen的返回值更新文本框.

我只是不知道如何连接这两个.

Dav*_*vid 6

首先,您需要更改您的班级名称." 进程 "是类库中类的名称,可能会使读取代码的任何人感到困惑.

让我们假设,对于本答案的其余部分,您将类名更改为MyProcessor(仍然是一个坏名称,但不是一个众所周知的,经常使用的类.)

此外,您缺少要检查的代码以确保用户输入确实是0到9之间的数字.这在Form的代码而不是类代码中是合适的.

  • 假设TextBox被命名为textBox1(VS为第一个添加到表单的TextBox生成默认值)
  • 进一步假设按钮的名称是button1

在Visual Studio中,双击按钮以创建按钮单击事件处理程序,如下所示:

protected void button1_Click(object sender, EventArgs e)
{

}
Run Code Online (Sandbox Code Playgroud)

在事件处理程序中,添加代码使其如下所示:

 protected void button1_Click(object sender, EventArgs e)
 {
   int safelyConvertedValue = -1;
   if(!System.Int32.TryParse(textBox1.Text, out safelyConvertedValue))
   {
     // The input is not a valid Integer value at all.
     MessageBox.Show("You need to enter a number between 1 an 9");
     // Abort processing.
     return;
   }

   // If you made it this far, the TryParse function should have set the value of the 
   // the variable named safelyConvertedValue to the value entered in the TextBox.
   // However, it may still be out of the allowable range of 0-9)
   if(safelyConvertedValue < 0 || safelyConvertedValue > 9)
   {
     // The input is not within the specified range.
     MessageBox.Show("You need to enter a number between 1 an 9");
     // Abort processing.
     return;
   }

   MyProcessor p = new MyProcessor();
   textBox1.Text = p.AddTen(safelyConvertedValue).ToString();
 }
Run Code Online (Sandbox Code Playgroud)

正确设置了访问修饰符的类应如下所示:

namespace addTen       
{       
    public class MyProcessor
    {       
        public int AddTen(int num)       
        {       
            return num + 10;       
        }       
    }       
}    
Run Code Online (Sandbox Code Playgroud)

  • 不要过多地混淆水域,但您也可以更改AddTen函数以接受字符串输入,并在该函数内进行验证.这实际上是我的偏好,并且会将更多的业务逻辑移出表单,但无论哪种方式都有效. (2认同)