软件编程
位置:首页>> 软件编程>> C#编程>> C#中单问号(?)和双问号(??)的用法整理

C#中单问号(?)和双问号(??)的用法整理

作者:springsnow  发布时间:2021-08-27 02:50:53 

标签:C#,单问号,双问号

一、可空类型修饰符(?)

C#2.0里面实现了Nullable数据类型

//A.比如下面一句,直接定义int为null是错误的,错误提示为无法将null转化成int,因为后者是不可以为null的值类型。
private int getNum = null;

//B.如果修改为下面的写法就可以初始指为null,在特定情况下?等同于基础类型为Nullable。
private int? getNum = null;
private Nullable<int> getNumNull = null;

二、三元运算符(?:)

需要if语句来判断,当Request.Params["para"]不为null时,取出para的值。

string strParam =Request.Params["para"];  
if ( strParam== null )  
{  
   strParam= "";  
}

用三元运算符?简化写法,取出para的值。

string strParam=Request.Params["para"] == null ? "":Request.Params["para"];

三、null合并运算符(??)

?? 运算符称为&ldquo; null 合并运算符&rdquo;,用于定义可以为 null 值的类型和引用类型的默认值。合并运算符为类型转换定义了一个预设值,以防可空类型的值为Null。

如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数。

int? x = null;//定义可空类型变量
int? y = x ?? 1000;//使用合并运算符,当变量x为null时,预设赋值1000
Console.WriteLine(y.ToString()); //1000

null 合并运算符为结合运算符,即操作时从右向左进行组合的。如,&ldquo;a??b??c&rdquo;的形式按&ldquo;a??(bb??cc)&rdquo;计算。

如果在尝试将可以为 null 值的类型分配给不可以为 null 值的类型时没有使用 ?? 运算符,则会生成编译时错误。如果使用强制转换,且当前还未定义可以为 null 值的类型,则会引发InvalidOperationException 异常。

//A.定义getNum为null,输出结果为0
private int? getNum = null;
Console.WriteLine(getNum ?? 0);

//B.定义getNum为1,输出结果为1
private int getNum = 1;
Console.WriteLine(getNum ?? 0);

四、NULL条件运算符(?.)

在C# 6.0中,引入了一个 ?. 的运算符。

如果对象为NULL,则不进行后面的获取成员的运算,直接返回NULL

void Main()
{

//首先我们定义全局变量Person对象,有可能p为null的情况下取值。
   Person p = null;
   string telePhoneNo = string.Empty;  //定义telePhoneNo

//取Person的telePhoneNo
   //A.初始写法,if条件判断
   if (p != null)
   {
       if (p.Secret != null)
       {
           telePhoneNo = p.Secret.TelePhoneNo;
       }
   }

//B.三元运算符写法,单问号?
   telePhoneNo = p != null ? (p.Secret != null ? p.Secret.TelePhoneNo : "") : "";

//C. NULL检查运算符?.
   telePhoneNo = p?.Secret?.TelePhoneNo ?? "";
   Console.Write(telePhoneNo);
}

public class SecretByMySelf
{
   public string Password { get; set; }
   public string TelePhoneNo { get; set; }
}

public class Person
{
   public string Name { get; set; }
   public SecretByMySelf Secret { get; set; }
}

五、?[]"运算符:

用于在执行成员访问 (?.) 或索引 (?[) 操作之前,测试是否存在 NULL。 这些运算符可帮助编写更少的代码来处理 null 检查,尤其是对于下降到数据结构。

int? count = customers?[0]?.Orders?.Count();
// null if customers, the first customer, or Orders is null

来源:https://www.cnblogs.com/springsnow/p/10455585.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com