+-

我有这个基类:
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 was unhandled.
Unable to cast object of type DynamicGunsGallery.AK47 to type
DynamicGunsGallery.Module
所以问题是:为什么我不能将派生类转换为基类?
还有其他方法可以使用基类中的方法加载动态库并对其进行“控制”吗?
最佳答案
根据您的评论:
在您的子库中,您无法重新声明模块;您必须引用原始库中的模块.
在其中具有ak类的项目中添加对主项目的引用.
我还考虑更改命名空间,以使您很明显地看到正在运行两个库
点击查看更多相关文章
转载注明原文:C#-继承的类转换 - 乐贴网