【问题标题】:Late binding MissingMethodException后期绑定 MissingMethodException
【发布时间】:2016-08-06 17:40:50
【问题描述】:

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

【问题讨论】:

  • MessageBox 类没有公共构造函数,应该通过它的静态方法使用。

标签: c# late-binding missingmethodexception


【解决方案1】:

您在此行收到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-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2021-03-29
    • 2018-03-20
    • 2014-07-09
    相关资源
    最近更新 更多