2017-05-20 88 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