C# NullReferenceException解决案例讲解

这篇文章主要介绍了C# NullReferenceException解决案例讲解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

最近一直在写c#的时候一直遇到这个报错,看的我心烦。。。准备记下来以备后续只需。

参考博客:

https://segmentfault.com/a/1190000012609600

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

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

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

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

改正错误:

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

二、未初始化类实例

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

 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; } } }

修正以后:

 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; } } }

三、数组为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); } } }

 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); } } }

四、事件为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,然后你调用了它。可以参照该博客:

https://www.cnblogs.com/springword/p/6498254.html

以上就是C# NullReferenceException解决案例讲解的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程