NullReferenceException C#中的异常

NullReferenceException C#中的异常什么是NullReferenceException?(WhatisNullReferenceException?)NullReferenceExceptionisanexceptionanditthrowswhenthecodeistryingtoaccessareferencethatisnotreferencingtoanyobject….

大家好,欢迎来到IT知识分享网。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#)

using System;

class Sample
{
   
   
    public void SayHello()
    {
   
   
        Console.WriteLine("Hello World");
    }
}

class Program
{
   
   
    static void Main()
    {
   
   
        Sample s = null;

        try
        {
   
   
            s.SayHello();
        }
        catch (NullReferenceException e)
        {
   
   
            Console.WriteLine("EXCEPTION: "+e.Message);
        }
    }
}

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

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/20704.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信