C# NullReferenceException解決案例講解
最近一直在寫(xiě)c#的時(shí)候一直遇到這個(gè)報(bào)錯(cuò),看的我心煩。。。準(zhǔn)備記下來(lái)以備后續(xù)只需。
參考博客:
https://segmentfault.com/a/1190000012609600
一般情況下,遇到這種錯(cuò)誤是因?yàn)槌绦虼a正在試圖訪(fǎng)問(wèn)一個(gè)null的引用類(lèi)型的實(shí)體而拋出異常??赡艿脑颉?。
一、未實(shí)例化引用類(lèi)型實(shí)體
比如聲明以后,卻不實(shí)例化
using System;
using System.Collections.Generic;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
List<string> str;
str.Add("lalla lalal");
}
}
}

改正錯(cuò)誤:
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");
}
}
}

二、未初始化類(lèi)實(shí)例
其實(shí)道理和一是一樣的,比如:
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;
}
}
}

三、數(shù)組為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
這種我還沒(méi)有見(jiàn)過(guò)。但是覺(jué)得也是常見(jiàn)類(lèi)型,所以抄錄下來(lái)。
public class Demo
{
public event EventHandler StateChanged;
protected virtual void OnStateChanged(EventArgs e)
{
StateChanged(this, e);
}
}
如果外部沒(méi)有注冊(cè)StateChanged事件,那么調(diào)用StateChanged(this,e)會(huì)拋出NullReferenceException(未將對(duì)象引用到實(shí)例)。
修復(fù)方法如下:
public class Demo
{
public event EventHandler StateChanged;
protected virtual void OnStateChanged(EventArgs e)
{
if(StateChanged != null)
{
StateChanged(this, e);
}
}
}
然后在Unity里面用的時(shí)候,最常見(jiàn)的就是沒(méi)有這個(gè)GameObject,然后你調(diào)用了它??梢詤⒄赵摬┛停?/p>
https://www.cnblogs.com/springword/p/6498254.html
到此這篇關(guān)于C# NullReferenceException解決案例講解的文章就介紹到這了,更多相關(guān)C# NullReferenceException內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
可替代log4j日志的c#簡(jiǎn)單日志類(lèi)隊(duì)列實(shí)現(xiàn)類(lèi)代碼分享
簡(jiǎn)單日志類(lèi)隊(duì)列實(shí)現(xiàn)??砂刺熘茉履甏笮》指钗募???珊?jiǎn)單替代log4j2013-12-12
C# List實(shí)現(xiàn)行轉(zhuǎn)列的通用方案
本篇通過(guò)行轉(zhuǎn)列引出了System.Linq.Dynamic,并且介紹了過(guò)濾功能,具有很好的參考價(jià)值。下面跟著小編一起來(lái)看下吧2017-03-03
datagridview實(shí)現(xiàn)手動(dòng)添加行數(shù)據(jù)
這篇文章主要介紹了datagridview實(shí)現(xiàn)手動(dòng)添加行數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04

