zoukankan      html  css  js  c++  java
  • C#可为空引用类型 -0007

    NullReferenceException的困扰

    实际项目开发过程中,我们经常会遇到空引用错误:

    Solution solution = null;
    var result = solution.TwoSumOne(nums, 13);
    
    // 会报以下错误            
    Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
    

      

    一般的做法是:

    在访问实例成员前,先对实例成员进行判空处理。

    if(null != solution)
    {
       var result = solution.TwoSumOne(nums, 13);
    }
    

      

    如果能在编译时候,就能检查出来可能得空引用,岂不更好?

    nullable reference type

    C# 8.0引入可为空引用类型(nullable reference types)和非空引用类型(non-nullable reference types)。

    • nullable reference type

    string? name;
    • 类型后面不带 的变量,都为non-nullable reference type

    启用空引用类型

    在项目的csproj文件加入一行:

    <Nullable>enable</Nullable>

    针对代码:

    Solution solution = null;
    var result = solution.TwoSumOne(nums, 13);

    编译后,可以看到编译器会产生两个警告:

    Program.cs(13,33): warning CS8600: Converting null literal or possible null value to non-nullable type. 
    [/Users/zclmoon/myProjects/algorithm/csharp/TwoSum01/TwoSum.csproj]Program.cs(15,26): 
    warning CS8602: Dereference of a possibly null reference. 
    [/Users/zclmoon/myProjects/algorithm/csharp/TwoSum01/TwoSum.csproj]
    

      

  • 相关阅读:
    JS事件冒泡、事件捕获和事件委托
    实现英文字母排序
    JavaScript异步加载的四种方法
    JavaScript作用域与作用域链
    JavaScript 自定义属性 data-*
    asycn和await
    style collectd
    JavaScript如何比较两个数组的内容是否相同
    VScode插件开发--M2D文档转换插件
    BOM笔记
  • 原文地址:https://www.cnblogs.com/codesee/p/13027436.html
Copyright © 2011-2022 走看看