zoukankan      html  css  js  c++  java
  • Null-conditional Operators

    https://msdn.microsoft.com/en-us/library/dn986595.aspx

    x?.y – null conditional member access. Returns null if the left hand operand is null.

    a?[x] – null conditional indexing. Returns null if the left hand operand is null.

    正式在使用VS2015了,安装了配套的Resharper

    今天看到绿色的提示,Use null propagation

    /// <summary>
            /// 传感器配置事件(通知DeviceInfo)
            /// </summary>
            public event EventHandler<SensorConfigedEventArgs> SensorConfiged;
    
            public void OnSensorConfiged(SensorConfigedEventArgs e)
            {
                var handler = SensorConfiged;
                if (handler != null)
                {
                    handler(this, e);
                }
            }

    Resharper的优化

      var handler = SensorConfiged;
                handler?.Invoke(this, e);

    Used to test for null before performing a member access (?.) or index (?[) operation.

    These operators help you write less code to handle null checks, especially for descending into data structures.

    int? length = customers?.Length; // null if customers is null 
    Customer first = customers?[0];  // null if customers is null
    int? count = customers?[0]?.Orders?.Count();  // null if customers, the first customer, or Orders is null

    The last example demonstrates that the null-condition operators are short-circuiting.

    If one operation in a chain of conditional member access and index operation returns null, then the rest of the chain’s execution stops.

    Other operations with lower precedence in the expression continue.

    For example, E in the following always executes, and the ?? and == operations execute.

    A?.B?.C?[0] ?? E
    A?.B?.C?[0] == E

    Another use for the null-condition member access is invoking delegates in a thread-safe way with much less code. The old way requires code like the following:

    var handler = this.PropertyChanged;
    if (handler != null)
        handler(…)

    The new way is much simpler:

    PropertyChanged?.Invoke(e)

    The new way is thread-safe because the compiler generates code to evaluate PropertyChanged one time only, keeping the result in temporary variable.

    You need to explicitly call the Invoke method because there is no null-conditional delegate invocation syntax PropertyChanged?(e).

    There were too many ambiguous parsing situations to allow it.

  • 相关阅读:
    09-异常处理-成绩判断异常
    继承与多态———动手动脑
    课下作业04-2String的使用方法
    课下作业04-1字符串加密
    课下作业03-2动手动脑及验证
    课下作业03-1请写一个类,在任何时候都可以向它查询“你已经创建了多少个对象?
    课下作业02-动手动脑
    Myschool试题
    使用ADO.NET
    模糊查询和聚合函数
  • 原文地址:https://www.cnblogs.com/chucklu/p/4962773.html
Copyright © 2011-2022 走看看