与程序集的后期绑定

Late binding with assembly

我试着做一个后期绑定的例子。这样我就可以更好地理解早期绑定和后期绑定之间的区别。我这样试:

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);

而且我不知道如何解决这个问题。

谢谢。

所以,Assembly.GetType 显然返回了 null。让我们检查一下 the documentation 并找出它的含义:

Return Value
Type: System.Type
A Type object that represents the specified class, or null if the class is not found.

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

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