zoukankan      html  css  js  c++  java
  • C# Tip 巧用??运算符

    ?? MSDN注解:
     
    如果 ?? 运算符的左操作数非空,该运算符将返回左操作数,否则返回右操作数
    作为C# 2.0新增的一个运算符,实际使用中并不多,但是如果能够巧妙运用,会有意想不到的效果
    示例1,初始化对象
    public class Program
    {
    class MyClass {}

    static MyClass instance;
    static void Main()
    {
    //如果instance == null,则做初始化

    //常规写法:
    if(instance == null)
    {
    instance
    = new MyClass();
    }
    //??写法:
    instance = instance ?? new MyClass();
    }
    }
     
     
    示例2,函数返回值
     
    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()));
    }
    }
     
    这只是两个简单的例子,具体的应用要根据实际场合举一反三.
  • 相关阅读:
    2020软件工程作业02
    2020软件工程作业01
    并发编程—协程
    并发编程—线程
    并发编程—进程
    python网络编程总结
    前端-Javascript
    前端-jQuery
    前端-CSS
    前端-Html
  • 原文地址:https://www.cnblogs.com/bloodish/p/1990027.html
Copyright © 2011-2022 走看看