1.IsNullOrEmpty 确定三个字符串中的每个字符串是有一个值、为空字符串还是为空引用 //This example demonstrates the String.IsNullOrEmpty() method using System; class Sample { publicstaticvoid Main() { string s1 ="abcd"; string s2 =""; string s3 =null; Console.WriteLine("String s1 {0}.", Test(s1)); Console.WriteLine("String s2 {0}.", Test(s2)); Console.WriteLine("String s3 {0}.", Test(s3)); } publicstatic String Test(string s) { if (String.IsNullOrEmpty(s) ==true) return"is null or empty"; else return String.Format("(\"{0}\") is not null or empty", s); } } /**//* This example produces the following results: String s1 ("abcd") is not null or empty. String s2 is null or empty. String s3 is null or empty. */
可空类型可以表示基础类型的所有值,另外还可以表示 null 值。可空类型可通过下面两种方式中的一种声明: System.Nullable<T> variable - 或 - T? variable T 是可空类型的基础类型。T 可以是包括 struct 在内的任何值类型;但不能是引用类型。 有关可能使用可空类型的示例,请考虑普通的布尔变量如何能够具有两个值:true 和 false。不存在表示“未定义”的值。在很多编程应用中(最突出的是数据库交互),变量可存在于未定义的状态。例如,数据库中的某个字段可能包含值 true 或 false,但是它也可能根本不包含值。同样,可以将引用类型设置为 null,以指示它们未初始化。 这种不一致会导致额外的编程工作,如使用附加变量来存储状态信息、使用特殊值,等等。可空类型修饰符使 C# 能够创建表示未定义值的值类型变量。 可空类型示例 任何值类型都可用作可空类型的基础。例 int? i =10; double? d1 =3.14; bool? flag =null; char? letter ='a'; int?[] arr =newint?[10]; 可空类型的每个实例都具有两个公共的只读属性: HasValue HasValue 属于 bool 类型。当变量包含非空值时,它被设置为 true。 Value Value 的类型与基础类型相同。如果 HasValue 为 true,则说明 Value 包含有意义的值。如果 HasValue 为 false,则访问 Value 将引发 InvalidOperationException。 在此示例中,HasValue 成员用于在尝试显示变量之前测试它是否包含值。 int? x =10; if (x.HasValue) { System.Console.WriteLine(x.Value); } else { System.Console.WriteLine("Undefined"); } 也可以通过下面的方法测试是否包含值: int? y =10; if (y !=null) { System.Console.WriteLine(y.Value); } else { System.Console.WriteLine("Undefined"); } 显式转换 可空类型可强制转换为常规类型,方法是使用强制转换来显式转换或者通过使用 Value 属性来转换。例如: int? n =null; //int m1 = n; // Will not compile. int m2 = (int)n; // Compiles, but will create an exception if x is null. int m3 = n.Value; // Compiles, but will create an exception if x is null. 如果两种数据类型之间定义了用户定义的转换,则同一转换也可用于这些数据类型的可空版本。 隐式转换 可使用 null 关键字将可空类型的变量设置为空,如下所示: int? n1 =null; 从普通类型到可空类型的转换是隐式的。 int? n2; n2 =10; // Implicit conversion. 运算符 可空类型还可以使用预定义的一元和二元运算符,以及现有的任何用户定义的值类型运算符。如果操作数为空,这些运算符将产生一个空值;否则操作数将使用包含的值来计算结果。例如: int? a =10; int? b =null; a++; // Increment by 1, now a is 11. a = a *10; // Multiply by 10, now a is 110. a = a + b; // Add b, now a is null. 在执行可空类型的比较时,如果其中任一可空类型为 null,则比较结果将始终为 false。因此,一定不要以为由于一个比较结果为 false,相反的情况就会为 true。例如: int? num1 =10; int? num2 =null; if (num1 >= num2) { System.Console.WriteLine("num1 is greater than or equal to num1"); } else { // num1 is NOT less than num2 } ??运算符 int? c =null; // d = c, unless c is null, in which case d = -1. int d = c ??-1; 此运算符还可用于多个可空类型。例如: int? e =null; int? f =null; // g = e or f, unless e and f are both null, in which case g = -1. int g = e ?? f ??-1; bool? 可空类型可以包含三个不同的值:true、false 和 null。它们本身不能用于条件语句,如 if、for 或 while。