我正在学习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" });发布于 2016-08-06 18:01:12
您将在这一行中得到一个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" });https://stackoverflow.com/questions/38807064
复制相似问题