我嘗試做一個後期綁定的例子。以便我更好地理解早期綁定和遲到綁定之間的區別。我嘗試這樣的:與程序集的後期綁定
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);
我無法弄清楚如何解決這個問題。
謝謝。
那麼,你可以檢查,變量'CustomerType'是否爲'null'?從最可能的錯誤來判斷。那麼問題是爲什麼'hallo.GetType(「EarlyBindingVersusLateBinding.cust」);'返回'null'。最可能的情況是,類型的名稱是不同的。 (我也不知道蝙蝠,GetType是否允許相對命名空間路徑)您可以使用'hallo.GetTypes()'並列出程序集中的每個類型以瞭解更多信息。 – MrPaulch
當你花費一點時間來調試代碼時,這將是非常明顯的。如果傳遞錯誤的字符串,Assembly.GetType()返回* null *。下一個是Kaboom。考慮「客戶」而不是「客戶」。什麼讓你鍵入「cust」可能是真正的問題,很難猜測。 –