博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
NullReferenceException C#中的异常
阅读量:2530 次
发布时间:2019-05-11

本文共 1872 字,大约阅读时间需要 6 分钟。

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

阅读更多:

翻译自:

转载地址:http://cotzd.baihongyu.com/

你可能感兴趣的文章
总结(6)--- python基础知识点小结(细全)
查看>>
亿级曝光品牌视频的幕后设定
查看>>
ARPA
查看>>
JSP开发模式
查看>>
我的Android进阶之旅------>Android嵌入图像InsetDrawable的使用方法
查看>>
Detours信息泄漏漏洞
查看>>
win32使用拖放文件
查看>>
Android 动态显示和隐藏软键盘
查看>>
raid5什么意思?怎样做raid5?raid5 几块硬盘?
查看>>
【转】how can i build fast
查看>>
接口测试-jmeter
查看>>
js便签笔记(5)——Dean Edwards大牛的跨浏览器AddEvent()设计(不知道是不是jQuery事件系统的原型)...
查看>>
重构wangEditor(web富文本编辑器),欢迎指正!
查看>>
null?对象?异常?到底应该如何返回错误信息
查看>>
django登录验证码操作
查看>>
(简单)华为Nova青春 WAS-AL00的USB调试模式在哪里开启的流程
查看>>
UIScrollerView ,UIPageControl混搭使用,添加定时器,无限循环滚动
查看>>
图论知识,博客
查看>>
微信企业号开发之-如何获取secret 序列号
查看>>
2015年最新Android基础入门教程目录(完结版)
查看>>