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

来源:互联网 发布:windows杀死进程命令 编辑:程序博客网 时间:2024/05/16 10:26
1.单问号(?)

1.1 单问号运算符可以表示:可为Null类型,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 值的类型,则会引发InvalidOperationException 异常。

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

3.单问号(?)和双问号(??)一些个人使用的简化写法分享

//定义SecretByMySelf类//Password :个人密码//TelePhoneNo :个人电话号码public class SecretByMySelf{    public string Password { get; set; }    public string TelePhoneNo { get; set; } { get; set; }}//定义Person类//Name :姓名//Sex :性别//Age :年龄,可以为null//Secret :个人秘密public class Person{    public string Name { get; set; }    public string Sex { get; set; }    public Nullable<int> Age { get; set; }    public SecretByMySelf Secret { get; set; }}//首先我们定义全局变量Person对象,有可能p为null的情况下取值。Person p ;//定义telePhoneNo string telePhoneNo = string.Empty;A. 取Person的telePhoneNo (初始写法,if条件判断)if (p != null){    if (p.Secret!= null)    {        telePhoneNo = p.Secret.TelePhoneNo;    }}B.取Person的telePhoneNo (三元运算符写法,单问号?)telePhoneNo = p == null ? (p.Secret == null ? p.Secret.TelePhoneNo : "") : "";C.取Person的telePhoneNo (合并运算符和三元运算符联合写法,单问号?和双问号??)telePhoneNo = p?.Secret.TelePhoneNo ?? "";

上面的三种写法都可以在不报异常的情况下取得telePhoneNo的值,方法之间也不存在好坏之分,只是写法的不同更加清晰了代码的书写量,每个Coding都有自己习惯的写法,适合自己的才是最好的。如有写错或者不明白的地方请即使提醒更正,感谢。

1 0
原创粉丝点击