首 页IT知识库收藏内容
当前位置:翔宇亭IT乐园IT知识库C#C#基础

C#中??运算符的使用方法

减小字体 增大字体 作者:不详  来源:转载整理  发布时间:2012-04-22 15:40:30

??是C#2.0中新增的一个运算符,可以认为是三元操作符?:的简版,其主要作用是如果 ?? 运算符的左操作数非空,该运算符将返回左操作数,否则返回右操作数。如果能较好地使用此操作符,将会得到意想不到的效果。

public class Program
{
  
class MyClass {}
   
  
static MyClass instance;
  
static void Main()
   {
      
//如果instance == null,则做初始化 
     
      
//常规写法:
       if(instance == null)
       {
          instance
= new MyClass();
       }
      
//使用??的写法:
       instance = instance ?? new MyClass();
   }
}

也可以用于函数的返回值中:

public class Program
    {
       
public string Str1 { get; set; }
       
public string Str2 { get; set; }
       
public string Str3 { get; set; }
       
//如果Str1不为NULL返回Str1,否则Str2,以此类推
        public override string ToString()
        {
           
//if-else常规写法
              if (Str1 != null)
            {
               
return Str1;
            }
           
else if (Str2 != null)
            {
               
return Str2;
            }
           
else if (Str3 != null)
            {
               
return Str3;
            }
           
else
            {
               
return base.ToString();
            }
           
//?:运算符写法
              return Str1 != null ? Str1 : (Str2 != null ? Str2 : (Str3 != null ? Str3 : base.ToString()));
           
//??运算符写法
             return Str1 ?? (Str2 ?? (Str3 ?? base.ToString()));
        }
    }

微信搜索“优雅的代码”关注本站的公众号,或直接使用微信扫描下面二维码关注本站公众号,以获取最新内容。

个人成长离不开各位的关注,你的关注就是我继续前行的动力。

知识评论评论内容只代表网友观点,与本站立场无关!

   评论摘要(共 0 条,得分 0 分,平均 0 分) 查看完整评论
愿您的精彩评论引起共鸣,带来思考和价值。
用户名: 查看更多评论
分 值:100分 90分 80分 70分 60分 40分 20分
内 容:
验证码:
关于本站 | 网站帮助 | 广告合作 | 网站声明 | 友情连接 | 网站地图
本站部分内容来自互联网,如有侵权,请来信告之,谢谢!
Copyright © 2007-2024 biye5u.com. All Rights Reserved.