动态分配字段

问题描述 投票:1回答:1

我正在尝试生成用于将字段值动态分配给动态类的代码。基本上,我理想上可以做到的就是达到这种效果:

il.Emit(OpCodes.Ldarg_0); // Object instance
il.Emit(OpCodes.Ldc_I4_0); // Value to assign to the field
il.Emit(OpCodes.Ld???, fieldInfo); // FieldInfo to assign the value to
il.Emit(OpCodes.Stfld); // Some kind of Stfld that pops the field and the value and assigns it

我找不到任何适合我需要的说明。我的另一个想法是为每个字段生成一个setter方法并调用该方法,但是我没有找到一种无需将其转换为Delegate即可完成的方法,该Delegate生成了[[很多样板代码。

有人有更好的解决方案吗?

编辑:问题是必须在堆栈上找到需要分配的字段,并在分配时间到来时以某种方式弹出该字段。不幸的是,没有一个CIL指令支持弹出一个fieldInfo分配给它,但是也许还有其他我没有想到的解决方案。

c# cil reflection.emit fieldinfo
1个回答
0
投票
当我在方法中分配字段时,反编译器将产生以下代码

// (no C# code) IL_0000: nop // x = 3; IL_0001: ldarg.0 IL_0002: ldc.i4.3 IL_0003: stfld int32 ConsoleApp1.Program::x // }

来自方法

class Program { int x; void Method() { x = 3; } }

© www.soinside.com 2019 - 2024. All rights reserved.