我是靠谱客的博主 高兴寒风,这篇文章主要介绍C# NullReferenceException解决案例讲解,现在分享给大家,希望可以做个参考。

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

参考博客:

https://segmentfault.com/a/1190000012609600

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

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

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
using System; using System.Collections.Generic; namespace Demo { class Program { static void Main(string[] args) { List<string> str; str.Add("lalla lalal"); } } }

改正错误:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
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"); } } }

二、未初始化类实例

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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; } } }

修正以后:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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

比如:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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); } } }

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

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

复制代码
1
2
3
4
5
6
7
8
9
public class Demo { public event EventHandler StateChanged; protected virtual void OnStateChanged(EventArgs e) { StateChanged(this, e); } }

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

修复方法如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
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解决案例讲解的文章就介绍到这了,更多相关C# NullReferenceException内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!

最后

以上就是高兴寒风最近收集整理的关于C# NullReferenceException解决案例讲解的全部内容,更多相关C#内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(116)

评论列表共有 0 条评论

立即
投稿
返回
顶部