2013-02-10 83 views
3

我有這個基類:繼承類鑄件

namespace DynamicGunsGallery 
{ 
    public class Module 
    { 
     protected string name; 

     public virtual string GetName() { return name; } 
     public virtual string GetInfo() { return null; } 
    } 
} 

和IM創建一個從基類,例如繼承動態庫(AK47.dll)

namespace DynamicGunsGallery 
{ 
    public class AK47 : Module 
    { 
     public AK47() { name = "AK47"; } 

     public override string GetInfo() 
     { 
      return @"The AK-47 is a selective-fire, gas-operated 7.62×39mm assault rifle, first developed in the USSR by Mikhail Kalashnikov. 
        It is officially known as Avtomat Kalashnikova . It is also known as a Kalashnikov, an AK, or in Russian slang, Kalash."; 
     } 
    } 
} 

我加載使用這個(inspired by this link)動態庫:在這兩個

namespace DynamicGunsGallery 
{ 
    public static class ModulesManager 
    { 
     public static Module getInstance(String fileName) 
     { 
      /* Load in the assembly. */ 
      Assembly moduleAssembly = Assembly.LoadFile(fileName); 

      /* Get the types of classes that are in this assembly. */ 
      Type[] types = moduleAssembly.GetTypes(); 

      /* Loop through the types in the assembly until we find 
      * a class that implements a Module. 
      */ 
      foreach (Type type in types) 
      { 
       if (type.BaseType.FullName == "DynamicGunsGallery.Module") 
       { 
        // 
        // Exception throwing on next line ! 
        // 
        return (Module)Activator.CreateInstance(type); 
       } 
      } 

      return null; 
     } 
    } 
} 

我已經包括了基類,我的可執行文件,包含ModuleManager會和dll庫。我在編譯的時候沒有問題,但是當我運行這段代碼我得到一個錯誤:

InvalidCastException was unhandled.

Unable to cast object of type DynamicGunsGallery.AK47 to type DynamicGunsGallery.Module

所以,問題是:爲什麼不能我投推導類的基類?

有沒有其他的方式來加載動態庫,並使用基類的方法「控制」它?

+3

是否有可能你有'Module'類在主程序中聲明兩次,即還有在'AK47.dll'中?您應該使用'typeof(Module).IsAssignableFrom(type)'調用來替換類型名稱字符串比較。 – 2013-02-10 11:50:03

+0

是的,我已經在主程序和庫中聲明瞭'Module'。我在主程序中使用它,因爲我想使用它的方法來控制庫,所以我猜主程序(compilator)必須知道它的聲明。而且我在圖書館有它,因爲每個圖書館都會從中得到,所以我再次猜測,彙編人員必須知道它的聲明能夠編譯出版物。我錯了嗎? ...我使用了字符串比較,因爲'typeof()'不適用於我。 – Buksy 2013-02-10 11:58:05

+0

另外,嘗試分割出你的最後一行,例如:'object something = activator.createinstance',然後'return(module)something'。設置一個斷點並確保某些東西是您期望的類型? – 2013-02-10 11:58:45

回答

3

從您的評論走向:

在你的子庫,你不能重新申報模塊;您必須從原始庫中引用該模塊。

添加對其中包含ak類的項目中的主項目的引用。

我還會想改變命名空間,使其明顯,你已經有了兩個庫回事

+0

謝謝:) ...即使'typeof()。IsAssignableFrom()'現在可以工作...是的,我會改變名稱空間也:) – Buksy 2013-02-10 12:16:39