简体   繁体   中英

Activator.CreateInstance() specific class type instance

this question is an addition to this previously asked question.

My child classes which should be initialised and the base class which will be the list type

abstract public class baseClass
{
    public baseClass()
    {
    }
}

public class child1 : baseClass
{
    public child1() : base
    {
    }
}

public class child2 : baseClass
{
    public child2() : base
    {
    }
}

My enum and manager class

public enum ClassType
{
    child1,
    child2
}

public class Manager
{
    private List<baseClass> _children;

    public void Initialise(ClassType type)
    {
        var temp = Activator.CreateInstance(null, type.ToString()); 
        //null = assembly which means this assembly
        _children.Add(temp);
    }
}

The manager class has been updated into the suggested answer from my previous question. However something is still wrong. In the case above I get the error: TypeLoadException was unhandled: Could not load type 'child2' from assembly 'Something' how can I change this? I did try some other options without success. (some resulting in a creation of the class but when adding resulting in a nullReferenceException).

EDIT :

Okay I changed my code into:

string assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
Type objType = Type.GetType(string.Format("{0}.{1},{0}", assemblyName, type.ToString()));
var temp = (baseClass)Activator.CreateInstance(objType, 1);
// 1 is the parameter I need to add to the constructor.
_children.Add(temp);

now I get the correct class created, but I get a NullReferenceException when I add the class to the list :(

Likely its not finding the type because the classes are potentially namespaced.

I mean that the typename for child2 might not just be child2 but rather be SomeNamespace.child2 .

Aside This seems like a really crazy pattern and I would advise taking a baseClass in the constructor instead.

Your code, as provided, wont even compile or work as expected also because of this: Activator.CreateInstance returns System.Runtime.Remoting.ObjectHandle and not actually the type you created. Of course you need to cast it to baseClass .
Besides that, you need to provide the name space when using this method, as suggested by Danilel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM