Update:
For the out parameter, we recommend that you read this article:
. Net (C #): more thorough understanding of out parameters from Il and Reflection emit
This document describes how to create two dynamic methods using the dynamicmethod type, including the ref and out parameters.
First, let's look at a simple method:
Static int add (ref int I, int count)
{
Return I + = count;
}
Let's create a dynamic method to execute the above function and then call it.
Code:
// + Using system. reflection;
// + Using system. reflection. emit;
VaR dynamicmethod = new dynamicmethod ("", typeof (INT), new type [] {typeof (INT). makebyreftype (), typeof (INT )});
Ilgenerator ilgen = dynamicmethod. getilgenerator ();
// I stack, Stack: I
Ilgen. emit (Opcodes. ldarg_0 );
// Copy I. The top I is used to obtain the specified integer. STACK: I, I
Ilgen. emit (Opcodes. DUP );
// Obtain the integer I represents. STACK: I, * I
Ilgen. emit (Opcodes. ldind_i4 );
// Count to stack. STACK: I, * I, count
Ilgen. emit (Opcodes. ldarg_1 );
// Add operation. STACK: I, * I + count
Ilgen. emit (Opcodes. Add );
// Assign a value. STACK: * I + count
Ilgen. emit (Opcodes. stind_i4 );
// Re-apply the updated I to the stack
Ilgen. emit (Opcodes. ldarg_0 );
// Obtain * I
Ilgen. emit (Opcodes. ldind_i4 );
// End
Ilgen. emit (Opcodes. Ret );
Next, call this dynamic method:
// Parameters:
VaR I =-3;
VaR COUNT = 10;
VaR Arg = new object [] {I, Count };
// Call a dynamic method
Int result = (INT) dynamicmethod. Invoke (null, ARG );
// Output result
Console. writeline (result );
Console. writeline (ARG [0]);
Output:
7
7
OK. The return value and the first parameter result are both 7.
Next let's take a look at the out parameter:
You will create a method like this:
Static void outobject (Out object OBJ)
{
OBJ = "hehe ";
}
Code:
// + Using system. reflection;
// + Using system. reflection. emit;
VaR dynamicmethod = new dynamicmethod ("", null, new type [] {typeof (object). makebyreftype ()});
// Set the ref parameter to out. (In fact, this program will be successfully executed without it)
Dynamicmethod. defineparameter (1, parameterattributes. Out, "OBJ ");
Ilgenerator ilgen = dynamicmethod. getilgenerator ();
// Import OBJ to stack
Ilgen. emit (Opcodes. ldarg_0 );
// Add hehe to the stack
Ilgen. emit (Opcodes. ldstr, "hehe ");
// Assign a value
Ilgen. emit (Opcodes. stind_ref );
// Exit
Ilgen. emit (Opcodes. Ret );
// Parameters:
VaR Arg = new object [] {null };
// Call a dynamic method
Dynamicmethod. Invoke (null, ARG );
// Output result
Console. writeline (ARG [0]);
Output:
Hehe