null(C# 参考)null (C# Reference)

null 关键字是表示不引用任何对象的空引用的文字值。The null keyword is a literal that represents a null reference, one that does not refer to any object. null 是引用类型变量的默认值。null is the default value of reference-type variables. 普通值类型不能为 null。Ordinary value types cannot be null. 但是,C# 2.0 引入了可以为 null 的值类型。However, C# 2.0 introduced nullable value types. 请参阅可以为 Null 的类型See Nullable Types.

下面的示例演示 null 关键字的一些行为:The following example demonstrates some behaviors of the null keyword:


 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 accessible 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# language specification

有关详细信息,请参阅 C# 语言规范For more information, see the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

请参阅See also