zoukankan      html  css  js  c++  java
  • C# 新特性 操作符单?与??和 ?. 的使用

    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;
    

    2.双问号(??)

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

    //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. ?.如果为空不报错误,不为空原值输出

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace ConsoleApp2
    {
        class Program
        {
            static void Main(string[] args)
            {
                myFun(null); // 123
                myFun("456");//  456
    
                Person personA = new Person() { name = "chenyishi" };
                Console.WriteLine(personA?.name);
    
                personA = null;
                Console.WriteLine(personA?.name);//person==null,仍不会报错
            }
    
    
            static void myFun(string argA)
            {
                Console.WriteLine(argA ?? "123"); //argA==null,则输出123
            }
        }
    
        class Person
        {
            public string name { get; set; }
        }
    }

    原文:

    https://www.cnblogs.com/appleyrx520/p/7018610.html

    https://www.cnblogs.com/chenyishi/p/8329752.html

  • 相关阅读:
    Python内置函数(14)——delattr
    Python内置函数(13)——complex
    Python内置函数(12)——compile
    Python内置函数(11)——classmethod
    Python内置函数(10)——chr
    Python内置函数(9)——callable
    Python内置函数(8)——bytes
    Python内置函数(7)——bytearray
    Python内置函数(6)——bool
    Python内置函数(4)——ascii
  • 原文地址:https://www.cnblogs.com/personblog/p/11105868.html
Copyright © 2011-2022 走看看