当前位置:网站首页>可空类型修饰符与空合并运算符

可空类型修饰符与空合并运算符

2023-01-19 15:33:01阿斯提尼

一、可空类型修饰符

可以让一个值类型赋值为null,例如给一个struct赋值为null或判断一个struct是否被赋过值

 		if(m_TestStruct != null) {
     }

"?"单问号:声明该值类型为可空类型

        static void Main(string[] args)
        {
    
            int? a = null;
            if (a == null)
            {
    
                Console.WriteLine("a为null");
            }
            Console.ReadKey();
        }

可空类型

声明一个可空类型有以下三种方式:

        int? a = null;
        int? b = new int?();
        Nullable<int> c = new Nullable<int>();

二、空合并运算符

"??"双问号(空合并运算符):类似于条件表达式,可以判断当一个类型为null时返回另一个值

        static void Main(string[] args)
        {
    
            int? a = null;
            int? b = 1;
            int c = 2;
            int d = a ?? c;
            int e = b ?? c;
            Console.WriteLine(d);
            Console.WriteLine(e);
            Console.ReadKey();
        }

空合并

注意:

  1. "??"的前面一个值必须是可空类型
  2. 空合并运算符为右结合运算符:a??b??c = a??(b??c)
  3. a??b??c??d??..??z的意义是返回第一个非空字符
原网站

版权声明
本文为[阿斯提尼]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43112045/article/details/88855556

随机推荐