zoukankan      html  css  js  c++  java
  • C# 6.0 (C# vNext) 新功能之:Null-Conditional Operator(转)

    Null-Conditional Operator 也叫 Null propagating operator 也叫 Safe Navigation Operator

    看名字,应该就有点概念了。如果还不知道,提示一下:
    有个叫 Conditional Operator 条件运算符(?:)
    也就是常会用到的:

    [csharp] view plain copy
     
    1. var result = (1 > 2) ? true : false;  


    当括号内的结果为 true 时,回传第一个值,如果为 false 回传第二个值。

    另外有一种:null-coalescing operator (??)
    比如:
    int? x = null;
    int y = x ?? -1;
    当 x 不为 null 时,则将其值给 y, 否则 y 被指定为 -1

    C# 6.0 新的 Null-Conditional Operator 应该可以叫做 null条件运算符
    使用如下:

    C# 6.0 之前的写法:

    [csharp] view plain copy
     
    1. var temp = GetCustomer();  
    2. string name = (temp == null) ? null : temp.name;  


    C# 6.0 的新写法

    [csharp] view plain copy
     
    1. var temp = GetCustomer()?.name;  


    也就是当 GetCustomer() 回传值不为 null 时,取 name 的值给 temp 变量

    其他的例子:

    [csharp] view plain copy
     
    1. x?.Dispose(); // 当 x 不为 null 时才呼叫 Dispose 方法  


    例子:

    [csharp] view plain copy
     
    1. event EventHandler OnFired;  
    2. void Fire()  
    3. {  
    4.     OnFired?.Invoke(this, new EventArgs());  
    5. }  


    当 OnFired 事件不为 null (有人注册该事件)时,才呼叫 Invoke 方法

    例子:
    以前的写法:

    [csharp] view plain copy
     
    1. public static string Truncate(string value, int length)  
    2. {  
    3.   string result = value;  
    4.   if (value != null)   
    5.   {  
    6.     result = value.Substring(0, Math.Min(value.Length, length));  
    7.   }  
    8.   return result;  
    9. }  


    新写法:

    [csharp] view plain copy
     
    1. public static string Truncate(string value, int length)  
    2. {            
    3.   return value?.Substring(0, Math.Min(value.Length, length));  
    4. }  

     

  • 相关阅读:
    android 启动报错
    android 百度地图
    android LayoutInflater使用
    spring mvc No mapping found for HTTP request with URI [/web/test.do] in DispatcherServlet with name 'spring'
    sql mysql和sqlserver存在就更新,不存在就插入的写法(转)
    jsp include
    json 解析
    css
    Scrapy组件之item
    Scrapy库安装和项目创建
  • 原文地址:https://www.cnblogs.com/lip-blog/p/7690868.html
Copyright © 2011-2022 走看看