以下代码抛出 Process is terminating due to StackOverflowException in the output。为什么?

Following code throws Process is terminating due to StackOverflowException in the output. Why?

我是 C# 的新手,下面是我的代码,当我 运行 它时,它抛出 Process is terminating due to WhosebugException in the output.Why??

namespace LearningCSharp
{
    class Program
    {
        //I have created the below object, I have not use it in main() method 
        //  but still because this ouput says WhosebugException
        Program ProgramObject = new Program();//removing "= new Program() " ,then it works fine

    static void Main(string[] args)
    {
        Program po = new Program();
        po.testing();
    }
    void testing()
    {
        Console.WriteLine("Testing is Ok");
    }
  }
}

主要问题是在自身内部创建 Program 的实例:

namespace LearningCSharp
{
    class Program
    {
        Program ProgramObject = new Program(); // The runtime will try to create an instance of this when the class is created (instantiated)... but since the class is creating an instance of itself, that instance will also try to create an instance and so on... this goes on forever until there isn't enough memory on the stack to allocate any more objects - a stack overflow.

        ... other code here
    }
}

控制台应用程序需要在应用程序启动时调用的静态方法:

static void Main(string[] args)

此静态方法无法查看实例成员 - 因此您需要将 testing() 方法设为静态:

    static void Main(string[] args)
    {
        testing();
    }

    static void testing()
    {
        Console.WriteLine("Testing is Ok");
    }

或创建另一个您可以实例化的class

namespace LearningCSharp
{
    class Program
    {

        static void Main(string[] args)
        {
            TestClass test = new TestClass();
            test.testing();
        }
    }
}

class TestClass 
{
    internal void testing()
    {
        Console.WriteLine("Testing is Ok");
    }
}

请注意,testing() 方法的访问器应该是 internalpublic,否则 Main class 将无法访问它。

您可以这样创建它:

class Program
{

    static Program programObject = new Program();

    static void Main(string[] args)
    {
        Program po = new Program();
        po.testing();
        Console.ReadLine();
    }

    void testing()
    {
        Console.WriteLine("Testing is working fine!!!");
    }
}

此致。