温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#中NullReferenceException怎么办

发布时间:2021-08-21 09:01:36 来源:亿速云 阅读:148 作者:小新 栏目:开发技术

小编给大家分享一下C#中NullReferenceException怎么办,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

一般情况下,遇到这种错误是因为程序代码正在试图访问一个null的引用类型的实体而抛出异常。可能的原因。。

一、未实例化引用类型实体

比如声明以后,却不实例化

using System; using System.Collections.Generic; namespace Demo {	class Program	{	static void Main(string[] args)	{	List<string> str;	str.Add("lalla lalal");	}	} }

C#中NullReferenceException怎么办

改正错误:

using System; using System.Collections.Generic; namespace Demo {	class Program	{	static void Main(string[] args)	{	List<string> str = new List<string>();	str.Add("lalla lalal");	}	} }

C#中NullReferenceException怎么办

二、未初始化类实例

其实道理和一是一样的,比如:

using System; using System.Collections.Generic; namespace Demo {	public class Ex	{	public string ex{get; set;}	}	public class Program	{	public static void Main()	{	Ex x;	string ot = x.ex;	}	} }

C#中NullReferenceException怎么办

修正以后:

using System; using System.Collections.Generic; namespace Demo {	public class Ex	{	public string ex{get; set;}	}	public class Program	{	public static void Main()	{	Ex x = new Ex();	string ot = x.ex;	}	} }

C#中NullReferenceException怎么办

三、数组为null

比如:

using System; using System.Collections.Generic; namespace Demo {	public class Program	{	public static void Main()	{	int [] numbers = null;	int n = numbers[0];	Console.WriteLine("hah");	Console.Write(n);	}	} }

C#中NullReferenceException怎么办

using System; using System.Collections.Generic; namespace Demo {	public class Program	{	public static void Main()	{	long[][] array = new long[1][];	array[0][0]=3;	Console.WriteLine(array);	}	} }

C#中NullReferenceException怎么办

四、事件为null

这种我还没有见过。但是觉得也是常见类型,所以抄录下来。

public class Demo {     public event EventHandler StateChanged;       protected virtual void OnStateChanged(EventArgs e)     {                 StateChanged(this, e);     } }

如果外部没有注册StateChanged事件,那么调用StateChanged(this,e)会抛出NullReferenceException(未将对象引用到实例)。

修复方法如下:

public class Demo {     public event EventHandler StateChanged;       protected virtual void OnStateChanged(EventArgs e)     {               if(StateChanged != null)         {               StateChanged(this, e);         }     } }

然后在Unity里面用的时候,最常见的就是没有这个GameObject,然后你调用了它。

以上是“C#中NullReferenceException怎么办”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI