gpt4 book ai didi

C#,将消息显示代码与业务逻辑分离

转载 作者:行者123 更新时间:2023-11-30 14:01:51 27 4
gpt4 key购买 nike

我有一个 winforms 应用程序,但我没有遵循任何类型的设计模式。我的问题是,我有这些包含我所有业务逻辑的基类。当发生异常或者我需要向用户显示一个对话框时,我将代码直接写到我需要它的基类中。

我知道我需要将我的业务逻辑和显示逻辑分开,所以我编写了一个静态类,其中包含显示消息所需的方法。

我的问题是,是否有更简单的方法将业务逻辑与显示分开?

我的静态方法是这样的,

public static void DisplayMessage(string message) 
{
MessageBox.Show(message);
}

public static bool DisplayDialogBox(string message,string caption )
{
DialogResult newresult = new DialogResult();

newresult = MessageBox.Show(message,caption,MessageBoxButtons.OKCancel);

if (newresult == DialogResult.OK)
{
return true;
}
else
{
return false;
}

所以我将从基类中调用这些方法,例如

MsgDisplay.DisplayMessage(e.Message);

这种方法是一种好的做法吗?

最佳答案

不,这种方法不是一个好习惯。您的类和 MessageBox 类之间没有任何区别。
和你的类(class)一起看:

MsgDisplay.DisplayMessage(e.Message);

并且只使用 MessageBox

MessageBox.Show(e.Message);

此包装器不提供任何附加功能。
如果你想分离业务逻辑和ui,那么你必须分解你的方法并只在UI层显示消息。
而且,小点。而不是:

if (newresult == DialogResult.OK)
{
return true;
}
else
{
return false;
}

只需输入:

return newresult==DialogResult.OK

更新:如果您只想显示异常消息,那么您应该捕获异常并在 UI 层上显示消息。所以在您的商务舱中而不是显示消息:

void foo() {
try {
//some code here
}
catch(FooException fe) {
MessageBox.Show(fe.Message);
}
}

向ui层抛出异常:

void foo() {
try {
//...
}
catch(FooException fe) {
//throw new BarException("Error occured: "+fe.Message); //if you want to customize error message.
throw; //If you don't need to change the message consider to not catch exception at all
}
}

然后在业务逻辑之外显示消息:

void fooButton_Click(object sender, EventArgs args) {
try {
fooBusinessClass.foo();
} catch(FooException fe) {
//if(MessageBox.Show(fe.Message)==DialogResult.OK) fooBusinessClass.continuefoo(); //if you have several options
MessageBox.Show(fe.Message);
}
}

关于C#,将消息显示代码与业务逻辑分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7479822/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com