The below code works only for calling methods without reference parameters.
public delegate void testD2(params object[] args);
public static testD2 SetTestD2(MethodInfo method)
{
ParameterExpression param = Expression.Parameter(typeof(object[]), "args");
ParameterInfo[] paramsInfo = method.GetParameters();
Expression[] argsExp = new Expression[paramsInfo.Length];
for (int i = 0; i < paramsInfo.Length; i++)
{
Expression index = Expression.Constant(i);
Type paramType = paramsInfo[i].ParameterType;
//??? ByRef removed from type, becuse Expression.Call with ByRef parametrs lead to compile error
if (paramType.IsByRef == true)
paramType = paramType.GetElementType();
//??? and for this reason is not change of parameters permanent
Expression paramAccessorExp = Expression.ArrayIndex(param, index);
Expression paramCastExp = Expression.Convert(paramAccessorExp, paramType);
argsExp[i] = paramCastExp;
}
var blockExp = Expression.Call(method, argsExp);
LambdaExpression result = Expression.Lambda(typeof(testD2), blockExp, param); //change in param?
return (testD2)result.Compile();
}
I am thinking to change the input parameters passed with params keyword, or create new params for lambda, but I don't know how.
public class testCls
{
public void Test()
{
MethodInfo mi = typeof(XXX).GetMethod("TestMethod");
var compiledObject2 = XXX.SetTestD2(mi);
int k = 5;
compiledObject2(k); //k is not passed as ByRef
}
}
public static void TestMethod(ref int a)
{
a = a * a;
}
refparameters, or could you return the appropriate values from the method? Do you have to use that delegate type, or could you use one that actually matches the method you're trying to call? Without more background, it's going to be hard to provide an answer.params object[]I'm assuming that theint(5) gets boxed and put in the array. That boxed value is now independant from the original value. If that boxed value is passed by ref, the underlying value ofkwon't change. That's why I think it might actually be passed by ref and you just won't notice it since it's now boxed in theobject[]and the original value isn't connected to that. Just one idea I had, I really don't know if that's a possibility.