小编给大家分享一下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");
}
}
}
改正错误:
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;
}
}
}
比如:
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);
}
}
}
这种我还没有见过。但是觉得也是常见类型,所以抄录下来。
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怎么办”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。