迟绑定MissingMethodException

问题描述:

我正在学习C#,目前在后期绑定章节。我为测试编写了以下内容,但它会生成MissingMethodException。我加载了一个自定义的私有DLL,并成功调用了一个方法,然后我试图用GAC DLL来做同样的事情,但是我失败了。迟绑定MissingMethodException

我不知道什么是错用下面的代码:

//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" }); 
+0

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

你是在这条线得到一个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" });