簡體   English   中英

創建具有新對象和沒有新對象的對象

[英]Create object with new and without new

我開始學習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 Box
Box* Box2 = new Box();   // Declare Box2 of type Box

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

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; }
}

也許您確實注意到我們Box中的Id尚未初始化。 這不是必需的(但是大多數時候您應該這樣做),因為它是一個值類型( struct )而不是一個防御類型( class )。

如果您想了解更多,請看以下問題: .NET中的struct和class有什么區別?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM