以下代码引发进程由于输出中的StackOverflowException而终止。为什么?

问题描述 投票:-1回答:2

我是C#的新手,以下是我的代码,当我运行它时,由于输出中的StackOverflowException,它抛出Process正在终止。为什么?

namespace LearningCSharp
{
    class Program
    {
        //I have created the below object, I have not use it in main() method 
        //  but still because this ouput says StackOverflowException
        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");
    }
  }
}
c# stack-overflow
2个回答
0
投票

主要问题是在其内部创建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");
    }

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

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类将无法访问它。


0
投票

您可以这样创建它:

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!!!");
    }
}

最诚挚的问候。

© www.soinside.com 2019 - 2024. All rights reserved.