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)用了它。可以參照該博客:
https://www.cnblogs.com/springword/p/6498254.html
到此這篇關(guān)于C# NullReferenceException解決案例講解的文章就介紹到這了,更多相關(guān)C# NullReferenceException內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#設(shè)計模式之Mediator中介者模式解決程序員的七夕緣分問題示例
這篇文章主要介紹了C#設(shè)計模式之Mediator中介者模式解決程序員的七夕緣分問題,簡單說明了中介者模式的定義并結(jié)合七夕緣分問題實例分析了中介者模式的具體使用技巧,需要的朋友可以參考下2017-09-09
c#不使用系統(tǒng)api實現(xiàn)可以指定區(qū)域屏幕截屏功能
這篇文章主要介紹了不使用系統(tǒng)API通過純c#實現(xiàn)屏幕指定區(qū)域截屏功能,截屏后還可以保存圖象文件,大家參考使用吧2014-01-01
C#使用WebClient登錄網(wǎng)站并抓取登錄后的網(wǎng)頁信息實現(xiàn)方法
這篇文章主要介紹了C#使用WebClient登錄網(wǎng)站并抓取登錄后的網(wǎng)頁信息實現(xiàn)方法,涉及C#基于會話操作登陸網(wǎng)頁及頁面讀取相關(guān)操作技巧,需要的朋友可以參考下2017-05-05

