Inherited class

I have this base class:

namespace DynamicGunsGallery
{
    public class Module
    {
        protected string name;

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

      

And Im creating dynamic libraries that inherit from a base class for example. (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.";
        }
    }
}

      

I am downloading dynamic libraries using this ( 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;
        }
    }
}

      

I have included the base class in both, my executable which contains the ModuleManager and the dll. I have no problem compiling, but when I run this code, I get an error:

InvalidCastException not handled.

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

So the question is: Why can't I distinguish the resulting class from the base class?

Is there another way to load a dynamic library and "control" it using methods from the base class?

+3


source to share


1 answer


Based on your comments:

In your helper library, you cannot re-declare a module; you have to reference the module from the source library.



Add a reference to the main project from a project that has ak class.

I also thought about changing the namespaces so that it is obvious that you have two libraries going to

+3


source







All Articles