reflection - 如何发出没有构造函数的新结构

标签 reflection struct reflection.emit

我试图发出动态方法,通过某些值设置类的字段,当常规字段的类型是结构时,我想使用新结构设置字段,如下所示: 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/

相关文章:

c# - 从另一个 AppDomain 的程序集中复制方法并从 CurrentDomain 执行它

java - 如何使用 Reflection API 正确泛化返回实例的方法?

scala - 在 akka Receive 中保存类型信息

c++ - 如何在 C++ 中将字符串变量的值赋给结构的字符串变量?

c# - 通过表达式树编译动态实例方法,具有私有(private)和 protected 访问权限?

c# - 复制/反射。发射静态数组

java - 如何从反射访问中过滤特定字段?

c# - 递归获取对象的属性和子属性

c - 为什么返回带结构的函数会出现计算错误

c - free 是否会从较小的结构指针中释放较大结构指针的所有内存?