【发布时间】:2010-09-28 06:45:56
【问题描述】:
以下面的类为例:
class Sometype
{
int someValue;
public Sometype(int someValue)
{
this.someValue = someValue;
}
}
然后我想使用反射创建这种类型的实例:
Type t = typeof(Sometype);
object o = Activator.CreateInstance(t);
通常这会起作用,但是因为SomeType 没有定义无参数构造函数,所以对Activator.CreateInstance 的调用将抛出MissingMethodException 类型的异常,并显示消息“没有为此对象定义无参数构造函数。 " 是否有另一种方法仍然可以创建这种类型的实例?将无参数构造函数添加到我的所有类中会有点糟糕。
【问题讨论】:
-
FormatterServices.GetUninitializedObject不允许创建未初始化的字符串。您可能会遇到异常:System.ArgumentException: Uninitialized Strings cannot be created.请记住这一点。 -
感谢您的提醒,但我已经分别处理字符串和基本类型了。
标签: c# reflection instantiation default-constructor