在代碼中我們經常能看到下面這樣的語句。
- A a = new A();(1)
- B b = null;(2)
- C c;(3)
代碼(1)
創建A的對象並對其進行初始化。
A:類;
new A():創建A的對象並對其初始化;
a:引用,指向new A()這個對象的引用。
注意:a不是A的對象,new A()纔是A的對象。
代碼(2)
聲明引用b,並指向null。
B:類;
b:引用,指向的對象爲null(空)。
代碼(3)
與代碼(2)一樣,聲明一個引用。
與代碼(2)的區別是:代碼(3)中聲明的引用c不指向任何對象。
提示:變量本質上是引用的一個別名而已。
由上面的分析可以瞭解到,在C#中實例化一個對象時,需要經歷下面這幾步:
- 聲明引用;
- 使用new關鍵字創建類的對象並對其初始化;(分配內存空間)
- 將引用指向類的對象。
若沒有使用new關鍵字創建類的實例,則僅僅創建引用,指向的對象爲null。
實例說明
- public class ExampleModel
- {
- public int C1 { get; set; }
- public string C2 { get; set; }
- }
- ExampleModel e1 = new ExampleModel();
- ExampleModel e2 = null;
- ExampleModel e3;
- if (e1 == null)
- {
- Console.WriteLine("e1 == null");
- }
- else
- {
- Console.WriteLine("{ C1 = " + e1.C1 + ", C2 = " + e1.C2 + " }");
- }
- if (e2 == null)
- {
- Console.WriteLine("e2 == null");
- }
- else
- {
- Console.WriteLine("{ C1 = " + e2.C1 + ", C2 = " + e2.C2 + " }");
- }
- if (e3 == null)
- {
- Console.WriteLine("e3 == null");
- }
- else
- {
- Console.WriteLine("{ C1 = " + e3.C1 + ", C2 = " + e3.C2 + " }");
- }
註釋掉e3 部分的代碼,運行程序得到下圖所示的結果。
在開發過程中,我們還是儘量不要讓一個引用指向null,否則在運行過程中很容易出現空引用的異常。
修改e2部分的代碼,去掉e2是否爲空引用的條件判斷,並運行程序。
運行中,會產生“未將對象引用設置到對象的實例。”的異常。(原因你懂的。)
同樣去掉e1部分中是否爲空引用的條件判斷語句,再次執行程序,一切正常。(因爲e1指向了不爲null的對象)
此文章源自於【http://blog.csdn.net/yl2isoft/article/details/23521083?utm_source=tuicool&utm_medium=referral】