Invoke Ref parameters
I've read the peter Ritchie's MVP blog
and come accross the issue that we met if we have a method that accept argument by reference . then we call it by reflection methodinfo.invoke(object,object[] params)
the issue is the params array that we passed did change but the variable "i" which is our main target remain the same :
class Program
{
private const int testValue = 10;
public static void TestMethod(ref int i)
{
i = testValue;
}
static void Main(string[] args)
{
MethodInfo methodInfo = typeof (Program).GetMethod("TestMethod", BindingFlags.Static | BindingFlags.Public);
int i = 0;
object[] parameters = new object[] {i};
methodInfo.Invoke(null, parameters);
// original variable isn't updated
Debug.Assert(i == 0);
// array element is updated:
Debug.Assert((int)parameters[0] == testValue);
// copy updated value to original variable
i = (int)parameters[0];
Debug.Assert(i == testValue);
}
}
}
To solve this use the Delegate.createdelegate
main function:Creates a delegate of the specified type to represent the specified static method.
http://msdn.microsoft.com/en-us/library/53cz7sc6.aspx
here's the code:
namespace EmitTesting
{
// delegate for void method that takes one reference parameter
public delegate void OneRefParameterCallback<T>(ref T value);
class Program
{
private const int testValue = 10;
public static void TestMethod(ref int i)
{
i = testValue;
}
static void Main(string[] args)
{
MethodInfo mi = typeof(Program).GetMethod("TestMethod");
var callback = (OneRefParameterCallback<int>)Delegate.CreateDelegate(typeof(OneRefParameterCallback<int>), mi);
int i = 0;
callback(ref i);
Debug.Assert(i == testValue);
}
}
}