2 回答

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超13個(gè)贊
是的,這是可能的,但是您必須了解以下兩行代碼之間的區(qū)別。
這是一個(gè)賦值示例:
a = 10;
這是帶有初始化程序的變量聲明示例。
var a = 10;
一個(gè)變量可以根據(jù)需要分配多次,但只能聲明一次(在一個(gè)范圍內(nèi))。
所以你絕對(duì)可以這樣做:
var enemy = new Enemy(); //Declaration
enemy = new Enemy(); //Assignment
enemy = null; //Assignment
enemy = new Enemy(); //Assignment
但你不能這樣做:
var enemy = new Enemy(); //Declaration
var 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;
}
}
上面的模式并不少見,使用后臺(tái)字段作為緩存并在即時(shí)的基礎(chǔ)上加載它。
如果你想要的只是像這樣的延遲加載,你也可以考慮使用一個(gè)Lazy<T>類。

TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
刪除 .net 中的對(duì)象是垃圾收集器的責(zé)任,因此您不必像在 C++ 中那樣刪除它們。
一旦沒有(根)引用該對(duì)象,垃圾收集器就會(huì)將其刪除。所以如果你只是重新分配變量,舊的對(duì)象將不再被引用,垃圾收集器將在一段時(shí)間后處理它。
如果對(duì)象被銷毀的那一刻很重要(它持有并且必須釋放一些重要的資源),那么你必須實(shí)現(xiàn)IDisposable.
Enemy enemy;
// ...
// time to create the enemy
enemy = new Enemy(); // creating the first one
// ... do something with the first enemy
// creating the second one
enemy = 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 destroyed
enemy = null;
- 2 回答
- 0 關(guān)注
- 262 瀏覽
添加回答
舉報(bào)