2013-02-10 86 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