1

我正在学习 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" });
4

1 回答 1

2

MissingMethodException你在这条线上得到一个:

object msb = Activator.CreateInstance(msBox);

因为类上没有公共构造函数MessageBox。这个类应该通过它的静态方法来使用,如下所示:

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" });
于 2016-08-06T18:01:12.663 回答