猿问

我可以在同一个变量上实例化多个对象吗?

例如:


Enemy enemy;

if(enemy == null)

{

    Enemy enemy = new Enemy();

}

如果这个敌人已经死了,以某种方式删除该实例并在上面声明的同一变量中重新实例化它。


编辑:我将它用于地牢爬虫控制台游戏,我希望,在你杀死怪物后,你会再次遭遇


明月笑刀无情
浏览 240回答 2
2回答

慕桂英4014372

是的,这是可能的,但是您必须了解以下两行代码之间的区别。这是一个赋值示例:a = 10;这是带有初始化程序的变量声明示例。var a = 10;一个变量可以根据需要分配多次,但只能声明一次(在一个范围内)。所以你绝对可以这样做:var enemy = new Enemy(); //Declarationenemy = new Enemy();&nbsp; &nbsp; &nbsp;//Assignmentenemy = null;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Assignmentenemy = new Enemy();&nbsp; &nbsp; &nbsp;//Assignment但你不能这样做:var enemy = new Enemy(); //Declarationvar enemy = new Enemy();&nbsp; //Declaration - will not compile回到您的示例,工作版本可能如下所示:class Game{&nbsp; &nbsp; private Enemy enemy = null; //You have to initialize a field before you can check it, even if you're just checking for null&nbsp; &nbsp; public Enemy GetEnemy()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (enemy == null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; enemy = new Enemy();&nbsp; //Here I am only assigning, not declaring&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return enemy;&nbsp; &nbsp; }}上面的模式并不少见,使用后台字段作为缓存并在即时的基础上加载它。如果你想要的只是像这样的延迟加载,你也可以考虑使用一个Lazy<T>类。

LEATH

删除 .net 中的对象是垃圾收集器的责任,因此您不必像在 C++ 中那样删除它们。一旦没有(根)引用该对象,垃圾收集器就会将其删除。所以如果你只是重新分配变量,旧的对象将不再被引用,垃圾收集器将在一段时间后处理它。如果对象被销毁的那一刻很重要(它持有并且必须释放一些重要的资源),那么你必须实现IDisposable.Enemy enemy;// ...// time to create the enemyenemy = new Enemy(); // creating the first one// ... do something with the first enemy// creating the second oneenemy = new Enemy();&nbsp;// now there's no reference to the first enemy and it will be destroyed// playing with second enemy// dropping the second enemy - it's not referenced now, too and&nbsp;// will be destroyedenemy = null;&nbsp;
随时随地看视频慕课网APP
我要回答