日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

NullReferenceException C#中的异常

發布時間:2025/3/11 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 NullReferenceException C#中的异常 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

什么是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:

  • Exception handling in C#

    C#中的異常處理

  • C# exception handling with multiple catch blocks

    具有多個catch塊的C#異常處理

  • User Defined Exceptions in C#

    C#中的用戶定義異常

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

總結

以上是生活随笔為你收集整理的NullReferenceException C#中的异常的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。