如何在 C# 中捕获空引用异常?


它处理因引用空对象而生成的错误。当您试图访问指向空值的成员字段或函数类型时,将发生空引用异常。

假设我们有一个这样的空字符串 -

string str = null;

现在,您尝试获取空字符串的长度,然后它将导致异常 -

If(str.Length == null) {}

上述异常将被抛出。现在,让我们看看如何防止抛出空指针异常 -

示例

 动态演示

using System;

class Program {
   static void Main() {
      int[] arr = new int[5] {1,2,3,4,5};
      display(arr);

      arr = null;
      display(arr);
   }

   static void display(int[] arr) {
      if (arr == null) {
         return;
      }
      Console.WriteLine(arr.Rank);
   }
}

输出

1

更新日期: 20-6 月-2020

247 次浏览

开启您的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.