我尝试做一个后期绑定的例子。以便我更好地理解早期绑定和迟到绑定之间的区别。我尝试这样的:与程序集的后期绑定
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”可能是真正的问题,很难猜测。 –