最近一直在写c#的时候一直遇到这个报错,看的我心烦。。。准备记下来以备后续只需。
参考博客:
https://segmentfault.com/a/1190000012609600
一般情况下,遇到这种错误是因为程序代码正在试图访问一个null的引用类型的实体而抛出异常。可能的原因。。
一、未实例化引用类型实体
比如声明以后,却不实例化
using System; using System.Collections.Generic; namespace Demo { class Program { static void Main(string[] args) { List<string> str; str.Add("lalla lalal"); } } }
改正错误:
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"); } } }
二、未初始化类实例
其实道理和一是一样的,比如:
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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)