第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

我可以在同一個(gè)變量上實(shí)例化多個(gè)對(duì)象嗎?

我可以在同一個(gè)變量上實(shí)例化多個(gè)對(duì)象嗎?

C#
明月笑刀無情 2021-06-03 13:16:48
例如:Enemy enemy;if(enemy == null){    Enemy enemy = new Enemy();}如果這個(gè)敵人已經(jīng)死了,以某種方式刪除該實(shí)例并在上面聲明的同一變量中重新實(shí)例化它。編輯:我將它用于地牢爬蟲控制臺(tái)游戲,我希望,在你殺死怪物后,你會(huì)再次遭遇
查看完整描述

2 回答

?
慕桂英4014372

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>類。


查看完整回答
反對(duì) 回復(fù) 2021-06-05
?
LEATH

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; 


查看完整回答
反對(duì) 回復(fù) 2021-06-05
  • 2 回答
  • 0 關(guān)注
  • 262 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)