我试图发出动态方法,通过某些值设置类的字段,当常规字段的类型是结构时,我想使用新结构设置字段,如下所示: var myStruct = new SomeStruct( );
。
但我找不到该结构的默认构造函数。
var type = valueForField.GetType ( );
if( type.IsValueType && !type.IsPrimitive && !type.IsEnum )
{
emit
.ldarg_0
.newobj ( type.GetConstructor( Type.EmptyTypes ) )
.stfld ( field );
continue;
}
它在 .newobj ( type.GetConstructor( Type.EmptyTypes ) )
行失败因为将 null 传递给 newobj 函数
有人可以告诉我如何通过默认构造函数发出新的结构创建吗?
最佳答案
使用initobj
.ldarg_0
.ldflda (field)
.initobj (type)
来自msdn:
Value types are not usually created using newobj. They are usually allocated either as arguments or local variables, using newarr (for zero-based, one-dimensional arrays), or as fields of objects. Once allocated, they are initialized using Initobj.
关于reflection - 如何发出没有构造函数的新结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9879874/