C# Winforms:避免执行代码或强制退出方法的正确方法
我经常使用Winforms,但我从未真正找到一种“全球公认的”退出方法 因此,我知道这是一种有效的方法,它可以确保在if(错误)中对我想要检查/停止的每一位代码进行分支 还有另外两种方法,但我不知道它们是否会导致意外行为 application.exit()是一个: 然后是Environment.exit(int)方法 建议?最佳实践?更正 什么都欢迎 该语句终止其出现的方法的执行,并将控制权返回给调用方法 从你最初的帖子和评论中的描述来看,这就是你想要的?因此,基本上使用如下内容,并以不同的方式处理返回值(返回0通常表示一切正常,而-1和其他可能的整数表示不同的错误类型。当然,如果只需要检查方法是否正确执行,甚至定义自己的异常,则可以使用布尔值)C# Winforms:避免执行代码或强制退出方法的正确方法,c#,winforms,exit,C#,Winforms,Exit,我经常使用Winforms,但我从未真正找到一种“全球公认的”退出方法 因此,我知道这是一种有效的方法,它可以确保在if(错误)中对我想要检查/停止的每一位代码进行分支 还有另外两种方法,但我不知道它们是否会导致意外行为 application.exit()是一个: 然后是Environment.exit(int)方法 建议?最佳实践?更正 什么都欢迎 该语句终止其出现的方法的执行,并将控制权返回给调用方法 从你最初的帖子和评论中的描述来看,这就是你想要的?因此,基本上使用如下内容,并以不同的方
为什么不使用try/catch块?还要完成什么?您只想退出方法并保持应用程序运行,还是让应用程序“崩溃”通过关闭它?
Environment.Exit
不会异常中断应用程序,而是强制终止它。那么Process.GetCurrentProcess().Kill()呢
?也就是说,您可以重构代码,将所有步骤作为接口或委托,循环执行这些步骤,然后使用一个方法在出现错误时抛出。@HW我没有捕获异常,没有真正的错误。我只是检查一个条件,在这个条件下我不希望执行某些代码。doctor,我必须尝试一下。我我不知道。顺便说一句,你的建议就像第一个if(错误)方法,只是使用委托而不是if。没有好处
bool error = false;
if (!error)
{
//do stuff
}
if(!error)
{
//do stuff
}
error = true;
if (!error)
{
//do stuff
}
bool error = false;
if (error)
{
Application.exit();
}
//do stuff
//code code code
if (error)
{
Application.exit();
}
//do stuff
//code code code
error = true;
if (error)
{
Application.exit();
}
//THIS CODE SHOULD NOT EXECUTE???? But i think it actually does...
//From what I understood it keep executing all the code in the method and then exits (message pumps and so on)
//do stuff
//code code code
bool error = false;
if (error)
{
Environment.exit();
}
//do stuff
//code code code
if (error)
{
Environment.exit();
}
//do stuff
//code code code
error = true;
if (error)
{
Environment.exit(1);
}
//THIS CODE SHOULD NOT EXECUTE BECAUSE Environment.exit(int) actually breaks the application with an exception
//Works but bad practice
//do stuff
//code code code
public int TestMethod(){
//do stuff
if (badStuffHappened)
{
return -1;
}
// Do more stuff which is not executed,
// if badStuffHappened before you reach the previous if statement.
return 0;
}