2017-04-19 58 views
0

我想在c#中學習reflection,並在學習過程中遇到此異常。如何解決mscorlib.dll錯誤中出現'System.ArgumentNullException'類型的未處理的異常

'System.ArgumentNullException' occurred in mscorlib.dll error 

如何解決這個問題?

class Program 
{ 
    static void Main(string[] args) 
    { 
     Assembly executingAssembly = Assembly.GetExecutingAssembly(); 

     Type customerType = executingAssembly.GetType("Reflection.Customer"); 
     object customerInstance = Activator.CreateInstance(customerType); 
     MethodInfo GetFullName = customerType.GetMethod("GetFullName"); 

     string[] methodParameter = new string[2]; 
     methodParameter[0] = "Minhaj"; 
     methodParameter[1] = "Patel"; 
     string Full_Name = (string)GetFullName.Invoke(customerInstance, methodParameter); 
     Console.WriteLine("Full Name = {0}", Full_Name); 
     Console.ReadKey(); 

    } 
} 

客戶類代碼

class Customer 
{ 
    public string GetFullName(string First_Name, string Last_Name) 
    { 
     return First_Name + " " + Last_Name; 

    } 
} 

enter image description here

回答

1

您需要檢查GetType方法的輸出,如果你的程序集沒有該對象。

例如:

Type t = assem.GetType("Transportation.MeansOfTransportation"); 
     if (t != null) { 

我已經採取了從https://msdn.microsoft.com/en-us/library/y0cd10tb(v=vs.110).aspx

這段代碼總之,任何調用之前,請確保您的對象/輸入不爲空。

+0

謝謝@PM,但這隻隱藏了我的'異常',但仍然沒有得到任何輸出,就像你說的檢查對象是否爲null,並且在' GetType'方法,我傳遞一個對象,即'GetType(「Reflection.Customer」);' –

+0

我猜這個例外是因爲你的GetType(「Reflection.Customer」);'返回null,因此是例外。 –

0

我想你在下面的一行中犯了一個錯誤。

Type customerType = executingAssembly.GetType("Reflection.Customer"); 

嘗試打印裝配類型並檢查它給客戶類別的全稱是什麼。

foreach(Type t in executingAssembly.GetTypes()) 
    { 
     Console.WriteLine(t.FullName.ToString()); 
    } 
相關問題