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)
要求是:
我只是不知道如何连接这两个.
首先,您需要更改您的班级名称." 进程 "是类库中类的名称,可能会使读取代码的任何人感到困惑.
让我们假设,对于本答案的其余部分,您将类名更改为MyProcessor(仍然是一个坏名称,但不是一个众所周知的,经常使用的类.)
此外,您缺少要检查的代码以确保用户输入确实是0到9之间的数字.这在Form的代码而不是类代码中是合适的.
在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)