可空值类型
可空值类型是System.Nullable
可空值类型除了可以正确的表示其底层数据类型的范围,还可以表示null
举例Nullable
bool
True
False
Nullable
True
False
Null
static void Main(string[] args)
{
string str = "asdfghjkl";
// 想要定位字母m在字符串中的哪个位置,如果没有的话返回null,int无法接收
Nullable<int> indexOfM = str.IndexOf('m');
//但是上面那样写比较麻烦,.NET提供了一个语法糖,用int?就可以表示可空类型
int? indexOfM2 = str.IndexOf('m');
}
Null和空,空白string
string name="Nick";
string name = null;
string name = "";
string name = " ";
判断Null和空,空白string
if(name==null){..} // 直接判断是否为null
if(string.isNullOrEmpty(name)){..} // 判断是否是null还是""的string
if(string.isNullOrWhiteSpace(name)){..}
// 判断是否包含空格的空string
static void Main()
{
string str = "";
System.Console.WriteLine(string.IsNullOrEmpty(str)); // True
System.Console.WriteLine(string.IsNullOrWhiteSpace(str)); // True
string str2 = null;
System.Console.WriteLine(string.IsNullOrEmpty(str2)); // True
System.Console.WriteLine(string.IsNullOrWhiteSpace(str2)); // True
string str3 = " ";
System.Console.WriteLine(string.IsNullOrEmpty(str3)); // False
System.Console.WriteLine(string.IsNullOrWhiteSpace(str3)); // True
}
Nullable的常用属性和方法
.HasValue //null:false; 否则:true
int? intValue = null;
System.Console.WriteLine(intValue.HasValue); // print:false
.Value // 底层值类型的值
static void Main()
{
int? intValue = 3;
System.Console.WriteLine(intValue.Value); // print:3
int? intValue2 = null;
// print: InvalidOperationException
System.Console.WriteLine(intValue2.Value);
}
.GetValueOrDefault() // 底层值类型的值或该类型的默认值
int? intValue = null;
System.Console.WriteLine(intValue.GetValueOrDefault()); // print:0
.GetValueOrDefault(默认值) // 底层值类型的值或指定的默认值
static void Main()
{
int? intValue = null;
System.Console.WriteLine(intValue.GetValueOrDefault(5)); // print:5
}
Nullable比较
static void Main()
{
int? a = 1;
int? b = 1;
System.Console.WriteLine(a == b); //True
int? c = 1;
int? d = null;
System.Console.WriteLine(c == d); //False
int? e = null;
int? f = null;
System.Console.WriteLine(e == f); //True
}
Nullable转换
T → Nullable<T>
隐式转换Nullable<T> → T
显示转换
static void Main()
{
{
int i = 3;
int? j = i;
}
{
int? i = 3;
//无法将类型“int?”隐式转换为“int”。存在一个显式转换(是否缺少强制转换?)
int j = i;
//只能显示转换
int j = (int)i;
}
}
检查Null的操作符
?: 条件操作符
?? Null合并操作符
?. Null条件操作符
?[ 针对索引表示法的操作预算