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

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 new 和不使用 new 創(chuàng)建對象

使用 new 和不使用 new 創(chuàng)建對象

C#
慕桂英546537 2022-12-31 13:03:19
我開始學(xué)習(xí) C#,我發(fā)現(xiàn)有兩種不同的方法來創(chuàng)建對象。首先是這樣的: Box Box1 = new Box();   // Declare Box1 of type Box Box Box2 = new Box();   // Declare Box2 of type Box其他是這樣的: Box Box1 ;   // Declare Box1 of type Box Box Box2 ;   // Declare Box2 of type Box兩種方法都有效,有什么區(qū)別?C++指針有類似的東西嗎?Box* Box1 = new Box();   // Declare Box1 of type BoxBox* Box2 = new Box();   // Declare Box2 of type Box
查看完整描述

1 回答

?
眼眸繁星

TA貢獻1873條經(jīng)驗 獲得超9個贊

您的第二個示例聲明了一個變量,但它將為空且無法訪問:


Box b;

int id = b.Id; // Compiler will tell you that you're trying to use a unassigned local variable 

我們可以通過用 null 初始化來欺騙編譯器:


Box b = null; // initialize variable with null

try

{

    int id = b.Id; // Compiler won't notice that this is empty. An exception will be trown

}

catch (NullReferenceException ex)

{

    Console.WriteLine(ex);

}

我們現(xiàn)在看到,我們必須初始化變量才能訪問它:


Box b; // declare an empty variable

b = new Box(); // initialize the variable


int id = b.Id; // now we're allowed to use it.

聲明和初始化的簡短版本是您的第一個示例:


Box b = new Box();

這是我用于示例的示例類:


public class Box

{

    public int Id { get; set; }

}

也許您確實注意到Id我們Box沒有被初始化。這不是必需的(但大多數(shù)時候您應(yīng)該這樣做),因為它是值類型 ( struct) 而不是引用類型 ( class)。

如果您想了解更多信息,請查看以下問題:.NET 中的結(jié)構(gòu)和類有何區(qū)別?


查看完整回答
反對 回復(fù) 2022-12-31
  • 1 回答
  • 0 關(guān)注
  • 109 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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