1: a null type
Nullable type is a value type System.Nullable <T> of the struct
Nullable types in addition to the correct value which represents the underlying data type (i.e., T) range, can also be expressed null
1.1: the following, bool value True and may be a type False, but can not be Null
Nullable <bool> In addition to an outer True and False, may also be Null
1.2: Nullable to write too much trouble, there are simple wording, only you need to add after the type, as follows?
2: Null, empty, empty string
string name = "John Doe"; // normal string, there is non-null string name1 = null; // value is null String NAME2 = ""; // string is an empty string name3 = ""; // whitespace string, is the space between the double quotes or Tab key
2.1: How to determine Null, empty, empty string
2.1.1: judge Null
string name = null; if (name == null) { //... }
2.1.2: Analyzing empty, that had nothing between double quotes following the method also comprises the case of string Null
string name2 = ""; if (string.IsNullOrEmpty(name2)) { //... }
2.1.3: Analyzing empty string, it may be an empty string, the string may be Null, use the following
string name3 = " "; if (string.IsNullOrWhiteSpace(name3)) { //... }
3: Nullable <T> common attributes and methods
.HasValue // If the value is null, the result is false; otherwise: true
.Value // Value underlying value type, if Nullable <T> is the value Null, will be reported abnormal
.GetValueOrDefault () // value of the underlying value type or the default value of that type, meaning that if your value is not Null, the value will return back; if it is Null, then return the default value of this value, int default value is 0, so the second return 0 FIG.
.GetValueOrDefault (default) // Default value or the bottom value of the specified type, meaning it can specify default values, not the underlying returns Null value type; if it returns a default value Null
4: Nullable <T> Conversion
T ---> Nullable <T> implicit conversion, because of the large range of values than in front of the rear, a Null value more
如下图:从范围小的a转换成范围大的b就直接隐式转换,前提这个范围大的要包含范围小的类型才可以
Nullable<T> ---> T ,反而言之,就得显示转换,如图一错二对:
如果值为Null,就会报异常,如图:
5:检查Null的操作符
条件操作符(三元运算符)?:
Null合并操作符 ?? 如果左边a不为Null,返回左边a的值;如果a为Null,返回b的值
Null条件操作符 ?.
Null条件操作符还有 ?[ 针对索引表示法的Nll条件操作符
6:string str = null,string str1 = “”,string str2 = string.empty;的区别
string str = null;在栈上有地址,但在堆上没有空间;null是string的默认值
string str1 =“”:空字符串,在栈和堆都有地址,并且堆上地址为空
string str2 = string.empty;它和str1差不多,在堆栈都为空间,不同就是在语法级上对str1的优化