C# NullReferenceException解決案例講解
最近一直在寫c#的時候一直遇到這個報錯,看的我心煩。。。準(zhǔn)備記下來以備后續(xù)只需。
參考博客:
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;
}
}
}

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

