直接上代码,知识点在代码中
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NullableDemo
{
class Program
{
static void Main(string[] args)
{
int? a; //a 与一般值类型区别是可为null 等同于 System.nullable<int> a;
//Console.WriteLine(a.ToString()); //未赋值前不能使用
a = null;
Console.WriteLine(a); //打出来的确为空
Console.ReadLine();
//int b; //一般值类型
//Console.WriteLine(b); //未赋值前不能使用
if (a == null)
{
Console.WriteLine("a's value is null");
}
Console.ReadLine();
if (a.HasValue) //如果 a 为 null 则为false
{
Console.WriteLine("a is not null");
}
else
{
Console.WriteLine("a is null");
}
Console.ReadLine();
int? a1 = 5;
int? a2 = a1 * 6;
Console.WriteLine(a2);
Console.ReadLine();
//int a3 = a1 * 6; //int? 无法隐式的转化成int 故不能编译通过,下面两种则可以
int a4 = (int)a1 * 6;
int a5 = a1.Value * 6;
Console.WriteLine(a5); //顺利通过
Console.ReadLine();
// ?? 空接合运算符 --只能用于 int? 和 int 之间
int? a6 = null;
int b = 3;
Console.WriteLine(a6 ?? b); // 返回3 如果第一个数 不为null,则返回第一个数,反之,返回第2个数
Console.ReadLine();
}
}
}