首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >后期结合MissingMethodException

后期结合MissingMethodException
EN

Stack Overflow用户
提问于 2016-08-06 17:40:50
回答 1查看 99关注 0票数 1

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

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

代码语言:javascript
复制
//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" });
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-06 18:01:12

您将在这一行中得到一个MissingMethodException

代码语言:javascript
复制
object msb = Activator.CreateInstance(msBox);

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

代码语言:javascript
复制
MessageBox.Show("Hi", "Message");

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

代码语言:javascript
复制
//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" });
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38807064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档