继承类转换

时间:2013-02-10 11:42:28

标签: c# casting

我有这个基类:

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

我正在使用此加载动态库(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 未处理。

     

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

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

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

1 个答案:

答案 0 :(得分:3)

从你的评论中得出:

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

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

我还考虑更改命名空间,以便明确表示您已经有两个库在继续