主方法后程序结束

时间:2018-09-22 17:06:39

标签: c# methods

我是C#的新手,我试图制作一个简单的计算器程序。但是,我的程序在执行main方法后立即结束。如何使其他方法也运行?

public static void Main(string[]args)
{
    string firstNum; 
    string secondNum;
    string mathOporaters;
}



public static void NumGather(string firstNum, string secondNum, string mathOporaters)
{
    Console.WriteLine("Please enter the symbol of the operation you wish to use.");
    mathOporaters = Console.ReadLine();
    if (mathOporaters == "+")
    {
        Console.WriteLine("Now enter the fist number you wish to use that oporater on");
        firstNum = Console.ReadLine();
        Console.WriteLine("And now enter the second number");
        secondNum = Console.ReadLine();

        double num1 = Convert.ToDouble(firstNum);
        double num2 = Convert.ToDouble(secondNum);
        char oporater = Convert.ToChar(mathOporaters);
        double answer = (num1 + num2);
    }
    else if (mathOporaters == "*")
    {
        Console.WriteLine("Now enter the fist number you wish to use that oporater on");
        firstNum = Console.ReadLine();
        Console.WriteLine("And now enter the second number");
        secondNum = Console.ReadLine();

        double num1 = Convert.ToDouble(firstNum);
        double num2 = Convert.ToDouble(secondNum);
        char oporater = Convert.ToChar(mathOporaters);
        double answer = (num1 * num2);
    }
    else if (mathOporaters == "/")
    {
        Console.WriteLine("Now enter the fist number you wish to use that oporater on");
        firstNum = Console.ReadLine();
        Console.WriteLine("And now enter the second number");
        secondNum = Console.ReadLine();
        double num1 = Convert.ToDouble(firstNum);
        double num2 = Convert.ToDouble(secondNum);
        char oporater = Convert.ToChar(mathOporaters);
        double answer = (num1 / num2);
    }
    else if (mathOporaters == "-")
    {
        Console.WriteLine("Now enter the fist number you wish to use that oporater on");
        firstNum = Console.ReadLine();
        Console.WriteLine("And now enter the second number");
        secondNum = Console.ReadLine();

        double num1 = Convert.ToDouble(firstNum);
        double num2 = Convert.ToDouble(secondNum);
        char oporater = Convert.ToChar(mathOporaters);
        double answer = (num1 - num2);

        else{
            Console.WriteLine("Im sorry, I don't understand the symbol you entered. Please use one of these: +,  -,  *, /");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您缺少一个非常基本的事实。我建议阅读this MSDN article

您可以阅读:

  

Main方法是C#应用程序的入口点。 (库和服务不需要Main方法作为入口点。)启动应用程序时,Main方法是被调用的第一个方法。

程序启动时,方法将放置在堆栈上。当堆栈为空时,应用程序结束

如上所述,Main()方法首先被调用,并且位于堆栈的底部。因此,完成后,应用程序结束。

总而言之,这是自然的行为。如果要运行定义的方法,则需要调用它们(例如,您可以阅读this)。

尝试一下:

public static void Main(string[]args)
{
    string firstNum; 
    string secondNum;
    string mathOporaters;
    // method call
    NumGather(firstNum, secondNum, mathOporaters);
}