2017-04-19 228 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()); 
    } 
相关问题