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

1、单问号(?)

1.1 表示Nullable类型

      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;

1.2 表示三元运算符

//A.需要if语句来判断,当Request.Params["para"]不为null时,取出para的值。
string strParam =Request.Params["para"];  
if ( strParam== null )  
 {  
    strParam= "";  
 }   

 //B.用三元运算符?简化写法,取出para的值。
string strParam=Request.Params["para"] == null ? "":Request.Params["para"];

2、双问号(??):null 合并运算符

?? 运算符称为 null 合并运算符,用于定义可以为 null 值的类型和引用类型的默认值。如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数。

可以为 null 的类型可以包含值,或者可以是未定义的。?? 运算符定义当可以为 null 的类型分配给非可以为 null 的类型时返回的默认值。

如果在尝试将可以为 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);

3、单问号(?)和双问号(??)联合写法

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. 合并运算符和三元运算符联合写法,单问号? 和双问号 ??
    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; }
}

猜你喜欢

转载自www.cnblogs.com/springsnow/p/10455585.html
今日推荐