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