无法创建生成类型的实例:没有为此对象定义无参数构造函数

Can't create instance of generated type: No parameterless constructor defined for this object

我正在生成新的动态类型并且不想创建它的实例。但是当实际创建实例化代码时,它会失败并出现异常:No parameterless constructor defined for this object.

我的代码如下:

AssemblyBuilder aBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("dfsdfsdf"), AssemblyBuilderAccess.Run);
ModuleBuilder mBuilder = aBuilder.DefineDynamicModule("dsadsadasdasda");
TypeBuilder typeBlank = mBuilder.DefineType("dasvvvvvvvv", TypeAttributes.Class | TypeAttributes.Public);
ConstructorBuilder cb = typeBlank.DefineDefaultConstructor(MethodAttributes.Public);
Type t = cb.GetType();
var item = Activator.CreateInstance(t);  // <--- Error appear in this line.

哪里出了问题?

您正在尝试创建 ConstructorBuilder 的实例,而不是您生成的 class。

我想你想要:

...
ConstructorBuilder cb = typeBlank.DefineDefaultConstructor(MethodAttributes.Public);
Type t = typeBlank.CreateType();
var item = Activator.CreateInstance(t);  

请注意,默认情况下会创建一个无参数的默认构造函数;除了以下情况,您不需要创建一个:

(来自 MSDN):

Because the default constructor is automatically defined, it is necessary to call this method only in the following situations:

  • You have defined another constructor and you also want a default constructor that simply calls the base class constructor.
  • You want to set the attributes on the default constructor to something other than PrivateScope, Public, HideBySig, SpecialName, and RTSpecialName.