简体   繁体   English

以下代码抛出进程因输出中的 StackOverflowException 而终止。 为什么?

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

I am new to C#, following is my code, when I run it, it throws Process is terminating due to StackOverflowException in the output.Why??我是 C# 新手,以下是我的代码,当我运行它时,它抛出 Process is termination due to StackOverflowException 在输出中。为什么?

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

The main issue is creating an instance of Program inside itself:主要问题是在其内部创建一个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
    }
}

A console application requires a static method that is called when the app starts:控制台应用程序需要一个在应用程序启动时调用的静态方法:

static void Main(string[] args)

This static method cannot see instance members - so you will either need to make your testing() method static:此静态方法无法看到实例成员 - 因此您需要将testing()方法设为静态:

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

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

or create another class that you can instantiate或创建另一个可以实例化的类

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

Note that the accessor for the testing() method should be internal or public or the Main class will not have access to it.请注意, testing()方法的访问器应该是internalpublic否则Main类将无法访问它。

You can create it like this:您可以像这样创建它:

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

Best regards.此致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM