using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { int? num = null; int a = num ?? -1; // ?? 如果num 为null 分配-1 Console.WriteLine(a); // Is the HasValue property true? if (num.HasValue) { System.Console.WriteLine("num = " + num.Value); } else { System.Console.WriteLine("num = Null"); } // y is set to zero int y = num.GetValueOrDefault(); // y=0; // num.Value throws an InvalidOperationException if num.HasValue is false try { y = num.Value; } catch (System.InvalidOperationException e) { System.Console.WriteLine(e.Message); } int? num1 = null; if (num1.HasValue) { Console.WriteLine("num" + num.Value); } else { Console.WriteLine("num=null"); } int z = num1.GetValueOrDefault(); try { z = num1.Value; } catch (Exception err) { Console.WriteLine(err.Message); } } } }
可以为 null 的类型具有以下特性:
-
值。)
-
这两种形式可以互换。
-
值
-
int j = x.GetValueOrDefault();
-
if(x.HasValue) j = x.Value;
-
false。
-
System.InvalidOperationException。
-
属性没有默认值。
-
if (x != null) y = x;
-
-
int? x = null; int y = x ?? -1;
-
Nullable<Nullable<int>> n;