如何在C#中进一步停止程序执行

Sha*_*lya 7 c#

string FirstName = Console.ReadLine();
            if (FirstName.Length > 12)
            {
                Console.WriteLine(".......................................");
            }
            if(FirstName.Length<3)
            {
                Console.WriteLine("....................");
            }
            Console.WriteLine("...................");
            string SecondName = Console.ReadLine();
            if (SecondName.Length > 12)
            {
                Console.WriteLine(".............................");
            }
            if(SecondName.Length<3)
            {
Run Code Online (Sandbox Code Playgroud)

我想停止程序,如果他们按下输入而没有输入值,怎么做?/?

Pra*_*een 8

string key = Console.ReadKey().ToString();  //Read what is being pressed
if(key == "") {
    Console.WriteLine("User pressed enter!");
    return; //stop further execution
}
Run Code Online (Sandbox Code Playgroud)


Nit*_*shi 6

我认为您希望有一个非空字符串值作为来自控制台的输入,如果输入为空,则想终止您的应用程序。使用以下代码:

Console.WriteLine("Enter a value: ");
string str = Console.ReadLine();
//If pressed enter here without a  value or data, how to stop the  program here without
//further execution??
if (string.IsNullOrWhiteSpace(str))
  return;
else
{
  Console.WriteLine(string.Format("you have entered: '{0}'", str));
  Console.Read();
}
Run Code Online (Sandbox Code Playgroud)

如果用户输入任何类型的空字符串或空格,则应用程序将在按回车键时终止。


chw*_*arr 5

Console.ReadLine()返回一个字符串。如果没有输入任何内容并且人们只是按下回车键,我们将得到一个空字符串。

对于不同的空定义,有多种方法可以测试字符串是否为“空”。空的一些常见定义以及如何测试它们:

  • null且不包含数据:myString.Length == 0
  • null或不包含数据:string.IsNullOrEmpty(myString)
  • null、空或只是空格:string.IsNullOrWhiteSpace(myString)

Environment.Exit()将使用您指定的退出代码结束该进程。

将上述测试之一与Environment.Exit()(可能还有if)相结合,您可以在没有“值或数据”时停止该过程。

另请注意,返回Main是退出进程的另一种方式。