[英]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?
在上述情况下,我得到错误:TypeLoadException未处理:无法从程序集“ Something”中加载类型为“ child2”的我该如何更改? I did try some other options without success.
我确实尝试了其他一些选择,但均未成功。 (some resulting in a creation of the class but when adding resulting in a nullReferenceException).
(有些导致类的创建,但添加时导致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 :( 现在我创建了正确的类,但是当我将类添加到列表中时,我得到了NullReferenceException :(
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
. 我的意思是,对于类型名
child2
可能不只是child2
而是要SomeNamespace.child2
。
Aside This seems like a really crazy pattern and I would advise taking a baseClass
in the constructor instead. 抛开这似乎是一个非常疯狂的模式,我建议
baseClass
在构造函数中使用baseClass
。
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. 由于以下原因,提供的代码甚至无法按预期进行编译或工作:
Activator.CreateInstance
返回System.Runtime.Remoting.ObjectHandle
而不是实际上创建的类型。 Of course you need to cast it to baseClass
. 当然,您需要将其
baseClass
为baseClass
。
Besides that, you need to provide the name space when using this method, as suggested by Danilel. 除此之外,如Danilel所建议的那样,在使用此方法时,您需要提供名称空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.