C#中的?修饰符

? 可空类型修饰符

// a代表可为空的int类型值
int? a; 

?: 三元(运算符)表达式

// b和c如果相等,那么a=1;否则a=0
var a=b==c?1:0;

?? 空合并运算符

// b如果为空,则a=c;否则a=b
var a=b??c;

?. NULL检查运算符

// Student如果为空,那么a=null;如果Student!=null,那么a=Student.Name
a=Student?.Name;

练习

var ret = new BasePageResponse<ProvinceResponse>()
{
    PageIndex = request?.PageIndex ?? PageVars.DefaultPageIndex,
    PageSize = request?.PageSize ?? PageVars.DefaultPageSize
};

解读:

  1. 如果request==null,那么PageIndex=PageVars.DefaultPageIndex;
  2. 如果request!=null,那么判断request.PageIndex是否为空?
    2.1 如果request.PageIndex==null,那么PageIndex=PageVars.DefaultPageIndex
    2.2 如果request.PageIndex!=null,那么PageIndex=request.PageIndex
原文地址:https://www.cnblogs.com/cndota2/p/13816141.html