2017-05-20 39 views
2

我尝试做一个后期绑定的例子。以便我更好地理解早期绑定和迟到绑定之间的区别。我尝试这样的:与程序集的后期绑定

using System; 
using System.Reflection; 

namespace EarlyBindingVersusLateBinding 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Customer cust = new Customer(); 


      Assembly hallo = Assembly.GetExecutingAssembly(); 

      Type CustomerType = hallo.GetType("EarlyBindingVersusLateBinding.cust"); 

      object customerInstance = Activator.CreateInstance(CustomerType); 

      MethodInfo getFullMethodName = CustomerType.GetMethod("FullName"); 

      string[] paramaters = new string[2]; 
      paramaters[0] = "Niels"; 
      paramaters[1] = "Ingenieur"; 

      string fullname = (string)getFullMethodName.Invoke(customerInstance, paramaters); 



      Console.WriteLine(fullname); 
      Console.Read(); 

     } 
    } 

    public class Customer 
    { 

     public string FullName(string firstName, string lastName) 
     { 

      return firstName + " " + lastName; 

     } 

    } 
} 

,但我得到这个异常:

An unhandled exception of type 'System.ArgumentNullException' occurred in mscorlib.dll 

Additional information: Value cannot be null. 

在这条线:

object customerInstance = Activator.CreateInstance(CustomerType); 

我无法弄清楚如何解决这个问题。

谢谢。

+0

那么,你可以检查,变量'CustomerType'是否为'null'?从最可能的错误来判断。那么问题是为什么'hallo.GetType(“EarlyBindingVersusLateBinding.cust”);'返回'null'。最可能的情况是,类型的名称是不同的。 (我也不知道蝙蝠,GetType是否允许相对命名空间路径)您可以使用'hallo.GetTypes()'并列出程序集中的每个类型以了解更多信息。 – MrPaulch

+0

当你花费一点时间来调试代码时,这将是非常明显的。如果传递错误的字符串,Assembly.GetType()返回* null *。下一个是Kaboom。考虑“客户”而不是“客户”。什么让你键入“cust”可能是真正的问题,很难猜测。 –

回答

3

所以,Assembly.GetType显然返回null。让我们来看看the documentation并找出这意味着什么:

返回值
类型:System.Type
表示指定的类,或为null如果找不到类的Type对象。

因此,无法找到类EarlyBindingVersusLateBinding.cust。这并不奇怪,因为这不是您的程序集中的有效类型。 cust是您的Main方法中的局部变量。你可能想写:

Type CustomerType = hallo.GetType("EarlyBindingVersusLateBinding.Customer"); 
+0

啊,谢谢!!那么即使是这样:// Customer cust = new Customer();不是必需的。 – LikeToDo

+0

@LikeToDo:确实如此。如果你在“外部”程序集上进行“真正的”后期绑定,你甚至不能这样做,因为编译器不会识别“客户”。 – Heinzi