C # How to call a method with an unknown number of parameters

I have reached the limit of my qualifications here. I don’t even know if this is possible, but I hope so.

I am doing a command handler (text). For each, Add()indicate the number of required parameters and their types. For instance:

void Add(string commandName, int requiredParameters, params Type[] paramTypes) { }
Add("test", 2, typeof(string), typeof(int));

So the example: command /test hello 7. The command handler checks if the types are correct, for example, it will fail if the second parameter is not converted to int.

Now the problem is that I want to pass the method to Add(). (The command handler will call this method if all the checks pass, and will call it with the required parameters). Thus, the method in question can have any number of parameters based on what was passed in Add().

How do I achieve this? The delegate does not work, he complains about inappropriate parameters. I tried to do something like:

void Add<T1, T2>(..., Action<T1, T2> method) { }
Add(..., new Action<string, int>(cmd_MyMethod));

But I would need to create an Add () method for many types. For example, Add<T1, T2, T3, T4, etc>and it also hurts to dial calls on Add().

I do not want to pass the method to call as a string, then use this.GetType().GetMethod()to get it. Although this method would be ideal, it gets confused when I obfuscate.

Does anyone know how to do this? Thanks in advance.

+5
source share
3 answers

Try the following:

void Add(string commandName, int requiredParameters, Delegate method) { }

method.DynamicInvoke(...), , . , , . .

, , :

Add("test", 2, new Action<string, int>(cmd_MyMethod));

, Type[], MethodInfo, !
(method.Method.GetParameters().Select(p => p.ParameterType).ToArray())

+3

Action<string, int, Type[]> Add.

:

public class ParamsTest
{
    public void CallMyMethod()
    {
        Action<string, int[]> myDelegate = new Action<string, int[]>(MyMethod);
        myDelegate("hello", new int[] { 1, 2, 3, 4 });
    }

    private void MyMethod(string arg1, params int[] theRest)
    {
        Console.WriteLine(arg1);
        foreach (int i in theRest)
        {
            Console.WriteLine(i);
        }
        Console.WriteLine("end");
    }
}
+3

, ( ) , . Invoke() MethodInfo .

0

All Articles