后期绑定 MissingMethodException

Late binding MissingMethodException

我正在学习 C#,目前正在学习后期绑定章节。我为测试编写了以下代码,但它生成了 MissingMethodException。我加载了一个自定义私有 DLL 并成功调用了一个方法,然后我尝试对 GAC DLL 执行相同的操作但我失败了。

我不知道下面的代码有什么问题:

//Load the assembly
Assembly dll = Assembly.Load(@"System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ");

//Get the MessageBox type
Type msBox = dll.GetType("System.Windows.Forms.MessageBox");

//Make an instance of it
object msb = Activator.CreateInstance(msBox);

//Finally invoke the Show method
msBox.GetMethod("Show").Invoke(msb, new object[] { "Hi", "Message" });

您在这一行收到 MissingMethodException

object msb = Activator.CreateInstance(msBox);

因为MessageBoxclass上没有public构造函数。此 class 应该通过其静态方法使用,如下所示:

MessageBox.Show("Hi", "Message");

要通过反射调用静态方法,您可以将 null 作为第一个参数传递给 Invoke 方法,如下所示:

//Load the assembly
Assembly dll =
    Assembly.Load(
        @"System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ");

//Get the MessageBox type
Type msBox = dll.GetType("System.Windows.Forms.MessageBox");

//Finally invoke the Show method
msBox
    .GetMethod(
        "Show",
        //We need to find the method that takes two string parameters
        new [] {typeof(string), typeof(string)})
    .Invoke(
        null, //For static methods
        new object[] { "Hi", "Message" });