当前位置:   article > 正文

NullReferenceException C#中的异常

nullreferenceexception

什么是NullReferenceException? (What is NullReferenceException?)

NullReferenceException is an exception and it throws when the code is trying to access a reference that is not referencing to any object. If a reference variable/object is not referencing to any object, then it will be considered as null. And, when the code tries to access this variable/object, there will be an exception known as NullReferenceException.

NullReferenceException是一个异常,当代码尝试访问未引用任何对象的引用时,将引发NullReferenceException 。 如果引用变量/对象未引用任何对象,则将其视为null 。 并且,当代码尝试访问此变量/对象时,将存在一个称为NullReferenceException的异常。

To handle NullReferenceException, we can write the code/message in catch block by using the NullReferenceException class.

为了处理NullReferenceException ,我们可以使用NullReferenceException类在catch块中编写代码/消息。

C#中的NullReferenceException示例 (Example of NullReferenceException in C#)

  1. using System;
  2. class Sample
  3. {
  4. public void SayHello()
  5. {
  6. Console.WriteLine("Hello World");
  7. }
  8. }
  9. class Program
  10. {
  11. static void Main()
  12. {
  13. Sample s = null;
  14. try
  15. {
  16. s.SayHello();
  17. }
  18. catch (NullReferenceException e)
  19. {
  20. Console.WriteLine("EXCEPTION: "+e.Message);
  21. }
  22. }
  23. }

Output

输出量

EXCEPTION: Object reference not set to an instance of an object

In the above program, we created a class "Sample" that contains a Method SayHello(), then we created another class that consumes class "Sample", then we create a reference of class "Sample" and assign null to reference s. We further called the method SayHello() using reference s, but it is not initialized properly. Thus, it generates NullReferenceException which is being caught in the catch block.

在上面的程序,我们创建了一个类“样本”,它包含一个方法的SayHello(),然后我们创建另一个类,消耗类的“样本”,然后我们创建一流的“样本”,并指定空的参考秒的参考。 我们还使用引用s调用了方法SayHello() ,但未正确初始化。 因此,它将生成NullReferenceException ,该异常将被捕获​​在catch块中。

Read more:

阅读更多:

翻译自: https://www.includehelp.com/dot-net/NullReferenceException-exception-in-csharp.aspx

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/100665
推荐阅读
  

闽ICP备14008679号