如何在不退出程序的情况下退出方法?

Nig*_*ce2 59 c# methods return exit

我仍然是C#的新手,与C/CPP相比,我很难习惯它.

如何在不退出程序的情况下退出C#上的函数,就像这个函数一样?

if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
    textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
System.Environment.Exit(0);
Run Code Online (Sandbox Code Playgroud)

这将不允许返回类型,如果单独留下它将继续通过未停止的函数继续.这是不可取的.

Mar*_*ers 134

有两种方法可以提前退出方法(不退出程序):

  • 使用return关键字.
  • 抛出一个例外.

例外情况只应用于特殊情况 - 当方法无法继续并且无法返回对调用者有意义的合理值时.通常你应该在完成后返回.

如果您的方法返回void,那么您可以在没有值的情况下编写return:

return;
Run Code Online (Sandbox Code Playgroud)

特别是关于你的代码:

  • 没有必要三次写相同的测试.所有这些条件都是等同的.
  • 在编写if语句时,您还应该使用花括号,这样就可以清楚if语句体内的哪些语句:

    if (textBox1.Text == String.Empty)
    {
        textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
    }
    return; // Are you sure you want the return to be here??
    
    Run Code Online (Sandbox Code Playgroud)
  • 如果您使用的是.NET 4,那么根据您的要求,您可能需要考虑使用一种有用的方法:String.IsNullOrWhitespace.

  • 可能想要使用Environment.Newline而不是"\r\n".
  • 除了将消息写入文本框之外,您可能还想考虑另一种显示无效输入的方法.


Sma*_*ery 8

除了Mark的答案之外,您还需要了解范围,使用大括号指定(在C/C++中).所以:

if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
    textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;
Run Code Online (Sandbox Code Playgroud)

总会在那时返回.然而:

if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
{
    textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
    return;
}
Run Code Online (Sandbox Code Playgroud)

只有在进入该if陈述时才会返回.