null (C# 參考)

更新: 2008 年 7 月

null 關鍵字是一個表示 Null 參考的常值,它不會參考其他物件。null 是參考型別 (Reference Type) 變數的預設值。一般實值型別 (Value Type) 不可以為 null。不過,C# 2.0 中增加了可為 null 的實值型別。如需詳細資訊,請參閱 可為 Null 的型別 (C# 程式設計手冊)

在下列範例中,會示範 null 關鍵字的某些行為:

class Program
{
    class MyClass
    {
        public void MyMethod() { }
    }

    static void Main(string[] args)
    {
        // Set a breakpoint here to see that mc = null.
        // However, the compiler considers it "unassigned."
        // and generates a compiler error if you try to
        // use the variable.
        MyClass mc;

        // Now the variable can be used, but...
        mc = null;

        // ... a method call on a null object raises 
        // a run-time NullReferenceException.
        // Uncomment the following line to see for yourself.
        // mc.MyMethod();

        // Now mc has a value.
        mc = new MyClass();

        // You can call its method.
        mc.MyMethod();

        // Set mc to null again. The object it referenced
        // is no longer accsessible and can now be garbage-collected.
        mc = null;

        // A null string is not the same as an empty string.
        string s = null;
        string t = String.Empty; // Logically the same as ""

        // Equals applied to any null object returns false.
        bool b = (t.Equals(s));
        Console.WriteLine(b);

        // Equality operator also returns false when one
        // operand is null.
        Console.WriteLine("Empty string {0} null string", s == t ? "equals": "does not equal");

        // Returns true.
        Console.WriteLine("null == null is {0}", null == null);


        // A value type cannot be null
        // int i = null; // Compiler error!

        // Use a nullable value type instead:
        int? i = null;

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();

    }
}

C# 語言規格

如需詳細資料,請參閱 C# 語言規格中的下列章節:

  • 2.4.4.6 null 常值

請參閱

概念

C# 程式設計手冊

參考

C# 關鍵字

常值關鍵字 (C# 參考)

其他資源

C# 參考

預設值表 (C# 參考)

變更記錄

日期

記錄

原因

2008 年 7 月

加入程式碼範例。

內容 Bug 修正。