我正在用 C# 和 XNA 制作一个游戏,目标是 Android 和 Windows Phone 7、7.1、8 等移动设备。它将使用一个名为 Minigame 的对象来确定玩家当前玩的游戏(一个迷你游戏设置在农场,另一个设置在城市,等等)。创建小游戏的代码是这样设置的。
public class Game1 : Microsoft.Xna.Framework.Game
{
//This is a global variable
Minigame minigame;
...
//This method loads the minigame when the player chooses one from the main menu
//It is loaded using an instance of a class that inherits from the Minigame class
void LoadMinigame(int number)
{
if (number == 0)
{
minigame = new MinigameOne();
}
else if (number == 1)
{
minigame = new MinigameTwo();
}
else
{
minigame = new MinigameThree();
}
}
}
迷你游戏总是使用对象的"new"实例加载,但是当迷你游戏完成并且玩家选择另一个时,永远不会有任何形式的删除。 C# 是否希望我做类似下面的事情,或者我在没有找到删除变量的方法的情况下一遍又一遍地继续使用“new”是否安全(即与下面相同的代码,减去删除命令)?
minigame = new MinigameOne();
//Do something with the minigame
delete minigame; //I don't think this command exists in C#, but is there an equivalent?
minigame = new MinigameTwo();
//Do something again
delete minigame;
minigame = new MinigameThree();
最佳答案
一旦对一个对象的所有引用都被删除,它就可以进行垃圾回收了。通过覆盖 minigame
中的引用,您将删除对先前 minigame 对象的引用。只要没有其他引用,一段时间后垃圾收集器就会将其吞噬。
我建议您阅读"The fundamentals of garbage collection"以便更好地了解对象如何到达其生命周期的尽头。
关于c# - 多次声明一个对象为 "new"会有什么后果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33058828/