2016-08-06 36 views
1

我正在學習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類沒有公共構造函數,它應該通過它的靜態方法來使用。 –

回答

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