亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

使用 new 和不使用 new 創建對象

使用 new 和不使用 new 創建對象

C#
慕桂英546537 2022-12-31 13:03:19
我開始學習 C#,我發現有兩種不同的方法來創建對象。首先是這樣的: 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兩種方法都有效,有什么區別?C++指針有類似的東西嗎?Box* Box1 = new Box();   // Declare Box1 of type BoxBox* Box2 = new Box();   // Declare Box2 of type Box
查看完整描述

1 回答

?
眼眸繁星

TA貢獻1873條經驗 獲得超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);

}

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


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沒有被初始化。這不是必需的(但大多數時候您應該這樣做),因為它是值類型 ( struct) 而不是引用類型 ( class)。

如果您想了解更多信息,請查看以下問題:.NET 中的結構和類有何區別?


查看完整回答
反對 回復 2022-12-31
  • 1 回答
  • 0 關注
  • 111 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號