欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C# NullReferenceException解決案例講解

 更新時(shí)間:2021年08月20日 11:36:12   作者:keneyr  
這篇文章主要介紹了C# NullReferenceException解決案例講解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下

最近一直在寫c#的時(shí)候一直遇到這個(gè)報(bào)錯(cuò),看的我心煩。。。準(zhǔn)備記下來以備后續(xù)只需。

參考博客:

https://segmentfault.com/a/1190000012609600

一般情況下,遇到這種錯(cuò)誤是因?yàn)槌绦虼a正在試圖訪問一個(gè)null的引用類型的實(shí)體而拋出異常。可能的原因。。

一、未實(shí)例化引用類型實(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");
		}
	}
}

二、未初始化類實(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

這種我還沒有見過。但是覺得也是常見類型,所以抄錄下來。

public class Demo
{
    public event EventHandler StateChanged;
 
    protected virtual void OnStateChanged(EventArgs e)
    {        
        StateChanged(this, e);
    }
}

如果外部沒有注冊(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í)候,最常見的就是沒有這個(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)文章

最新評(píng)論