How to load static field?

954 views Asked by At

I am generating a Type with static fields num1, num2, etc. via Reflection.Emit.

Now I do not know how to emit code which loads the contents of a static field in the generated type onto a static method's evaluation stack. What I have tried so far is:

generator.Emit(Opcodes.Ldarg, 0);
generator.Emit(Opcodes.Ldfld, "num1");

But clearly this can not work, because it tries to load an instance field on 'this', which is not supplied to the static method.

Which opcode should I use to access the static field?

1

There are 1 answers

2
M.Stramm On BEST ANSWER

Opcodes.Ldsfld

So, assuming you have created num1 somewhere like FieldBuilder num1 = ... before, you can load it onto the stack via generator.Emit(Opcodes.ldsfld, num1);