3

我有这个基类:

namespace DynamicGunsGallery
{
    public class Module
    {
        protected string name;

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

我创建了从基类继承的动态库,例如(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.";
        }
    }
}

我正在使用它加载动态库(受此链接启发):

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未处理。

无法将 DynamicGunsGallery.AK47 类型的对象转换为 DynamicGunsGallery.Module

所以问题是:为什么我不能将派生类转换为基类?

还有其他方法可以加载动态库并使用基类中的方法“控制”它吗?

4

1 回答 1

3

来自您的评论:

在您的子库中,您不能重新声明模块;您必须从原始库中引用该模块。

从包含 ak 类的项目中添加对主项目的引用。

我还考虑更改名称空间,以使您有两个库在运行

于 2013-02-10T12:00:51.817 回答