美文网首页
真会 C# 吗 09

真会 C# 吗 09

作者: JeetChan | 来源:发表于2019-06-25 17:30 被阅读0次

    声明

    本文内容来自微软 MVP solenovex 的视频教程——真会C#?- 第1-2章 简介和基础(完结),大致和第 12 课—— Null的操作符(入门) 对应。

    本文主要包括以下内容:

    1. Null 操作符

    Null 操作符

    C# 提供了两种操作符,它们可以更容易地处理 null。

    1. null 合并操作符。
    2. null 条件操作符。

    null 合并操作符

    ??符号表示,如果操作数不是 null,那么把它给我;否则的话,给我一个默认值。如果左边的表达式非 null,那么?右边的表达式就不会被计算。

    string s1 = null;
    string s2 = s1 ?? "nothing"; // s2 evaluates to "nothing"
    

    null 条件操作符(Elvis)

    C# 6 新特性中,允许你像点.操作符那样调用方法或成员,除非当左边的操作数是 null 的时候,那么整个表达式就是 null,而不会抛出 NullReferenceException 。一旦遇到 null,这个操作符就把剩余表达式给短路掉了。

    System.Text.StringBuilder sb = null;
    string s = sb?.ToString(); // No error; s instead evaluates to null, equivalent to: string s = (sb == null ? null : sb.ToString());
    
    System.Text.StringBuilder sb = null;
    string s = sb?.ToString().ToUpper(); // s evaluates to null without error
    

    使用 null 条件操作符,最终的表达式必须可以接受 null ;可以和 null 合并操作符一起使用。

    System.Text.StringBuilder sb = null;
    int length = sb?.ToString().Length; // Illegal : int cannot be null
    // int? length = sb?.ToString().Length; // OK : int? can be null
    
    System.Text.StringBuilder sb = null;
    string s = sb?.ToString() ?? "nothing"; // s evaluates to "nothing"
    
    Null Operator.png

    参考

    C# Null Coalescing and Null Conditional Operators

    null (C# Reference)

    ?? operator (C# reference)

    ?: operator (C# reference)

    Null-conditional operators

    相关文章

      网友评论

          本文标题:真会 C# 吗 09

          本文链接:https://www.haomeiwen.com/subject/xtuxcctx.html