我应该在循环内声明并创建类的实例吗?

发布于 2025-01-19 12:38:56 字数 640 浏览 1 评论 0原文

我编写了一个简单的控制台游戏(具体来说是 TicTacToe)用于练习。游戏结束后,我需要重置游戏,以便创建游戏类的新实例。

在创建新类之前是否销毁了类的旧实例?

如果没有,那么它就会堆积在内存中,这是不好的。那么这里更好的做法是什么?

        static void Main(string[] args)
        {
            bool restart = true;  //stores decision whether to restart the game
            do
            {
                Game game = new Game();  //a simple console game
                game.start();            //start -> play -> game over
                restart = playAgain();   //playAgain returns a boolean
            } while (restart);
        }

如果相关的话,代码是用 C# 编写的。

I wrote a simple console game (TicTacToe to be specific) for practice. After game over I need to reset the game so I am creating a new instance of the game class.

Is the old instance of class destroyed before creating the new one?

If not then it is getting stacked up in the memory which is not good. So what is the better practice here?

        static void Main(string[] args)
        {
            bool restart = true;  //stores decision whether to restart the game
            do
            {
                Game game = new Game();  //a simple console game
                game.start();            //start -> play -> game over
                restart = playAgain();   //playAgain returns a boolean
            } while (restart);
        }

The code is written in c# if that is relevant.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

喵星人汪星人 2025-01-26 12:38:56

简短版本:

我应该在循环内声明并创建类的实例吗?

是的,如果您只需要循环内的该实例。


当我们创建一个对象时

Game game = new Game();

……只要存在对它的引用,它就“存在”在内存中。当不再有任何对某个对象的引用时,该对象就可用于垃圾回收。

所以问题是,创建的 Game 对象有哪些引用?看起来只有一个引用,即您为其分配的 game 变量。

所以现在的问题是,这个变量能存活多久?它的存在时间与它定义的范围一样长。在本例中,您将在 do 循环中定义它。一旦循环执行结束(几行后),变量就会超出范围。换句话说,它定义的范围不再存在。简而言之,该变量不再存在。

该变量是对该确切 Game 对象的唯一引用。当变量超出范围时,不再有对该 Game 对象的任何引用。它将被垃圾收集。 (这不会立即发生,但我们不必担心它发生的确切时间。我们通常不关心。这是框架为我们担心的事情。)

如果循环重复怎么办?将该循环的内部视为一个被一遍又一遍调用的方法。当再次调用它时,game 变量是新的,因为它是在循环内声明的。它不“知道”有关先前执行的循环或先前的 Game 对象的任何信息。该变量在循环迭代结束时超出了范围。

我们如何知道变量的范围是什么?一种简单的方法是查看允许我们在哪里使用它。

如果您尝试编写此代码,请在循环之外使用 game 变量:

        static void Main(string[] args)
        {
            bool restart = true;  //stores decision whether to restart the game
            do
            {
                Game game = new Game();  //a simple console game
                game.start();            //start -> play -> game over
                restart = playAgain();   //playAgain returns a boolean
            } while (restart);

        }
        game.Start(); // <-- Outside the loop where it was declared

...它将无法编译。这是因为该变量是在循环内部声明的,因此它在循环外部不可用。就像我们在一个方法中声明局部变量一样,它在另一个方法中不可见或不可访问。

The short version:

Should I declare and create an instance of a class inside loop?

Yes, if you only need that instance inside the loop.


When we create an object

Game game = new Game();

...it "exists" in memory as long as there are references to it. When there are no longer any references to an object it becomes available for garbage collection.

So the question is, what references are there to the created Game object? It appears that there is only one reference, the game variable that you assign it to.

So now the question is, how long does that variable live? It lives as long as the scope within which it is defined. In this case you're defining it within a do loop. As soon as that execution of the loop is over (a few lines later) the variable goes out of scope. In other words, the scope within which it was defined no longer exists. In simpler terms, that variable no longer exists.

The variable is the only reference to that exact Game object. When the variable goes out of scope, there are no longer any references to that Game object. It will be garbage collected. (That doesn't happen instantly, but we don't have to worry about exactly when it happens. We don't usually care. That's something the framework worries about for us.)

What if the loop repeats? Think of the inside of that loop as a method that gets called over and over. When it gets called again, the game variable is new, because it's declared inside the loop. It doesn't "know" anything about the previous execution of the loop or the previous Game object. That variable went out of scope at the end of that iteration of the loop.

How do we tell what the scope of a variable is? One easy way is to see where we're allowed to use it.

If you tried to write this, using the game variable outside of the loop:

        static void Main(string[] args)
        {
            bool restart = true;  //stores decision whether to restart the game
            do
            {
                Game game = new Game();  //a simple console game
                game.start();            //start -> play -> game over
                restart = playAgain();   //playAgain returns a boolean
            } while (restart);

        }
        game.Start(); // <-- Outside the loop where it was declared

...it wouldn't compile. That's because the variable is declared inside the loop, so it's not available outside the loop. Just like if we declare a local variable inside one method it's not visible or accessible inside another method.

天气好吗我好吗 2025-01-26 12:38:56

据我所知(因为我对此比较陌生)您在 do 范围内声明的所有变量都是本地变量,当程序超出该范围时,这些变量将被销毁。因此,您在 do 作用域中声明的游戏类的实例是本地的,因此当 while 循环再次检查条件时将被销毁。

As far as I know (because I'm relatively new to this) all variables that you declare in the do scope are local, and when the program is out of that scope those variables are destroyed. So, the instance of the game class that you declare in the do scope is local and will therefore be destroyed when the while loop checks the condition again.

多彩岁月 2025-01-26 12:38:56

当您创建名为 game 的 Game 类的新实例时,您所做的就是将变量 game 设置为新实例。 game 保存在内存中,因此下次启动游戏时,它将采用变量 game 并且无论它处于什么状态,都会将其设置为新实例。这意味着该类的实例永远不会超过一次,无论它是否在 do/while 循环中,因为您使用的是相同的变量。

When you create a new instance of the Game class called game all you are doing is setting the variable game to a new instance. game is saved in memory so the next time you start a game it will take the variable game and regardless of what state it's in, will set it to a new instance. This means that there is never more than once instance of that class regardless of it being in a do/while loop because you are using the same variable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文