C# reflective method invocation with arbitrary number of parameters [duplicate]

StackOverflow https://stackoverflow.com/questions/23660137

  •  22-07-2023
  •  | 
  •  

سؤال

Trying to invoke a method with an arbitrary number of parameters:

Type objType = obj.GetType();
MethodInfo method = objType.GetMethod("InvokedMethod");
method.Invoke(obj, new string[] { "param1", "param2" });

The method signature looks like that:

public void InvokedMethod(params string[] args) { ... } 

Why I get following Exception:

System.Reflection.TargetParameterCountException (Parameter count mismatch)
هل كانت مفيدة؟

المحلول

The method doesn't accept two parameters, it accepts one parameter that is an array. The compiler will perform a transformation such that a method call of two strings will be transformed into a call of a single array with two values. That transformation won't be done for you when using reflection. You'll need to explicitly create an array and put the two values in it:

method.Invoke(obj, new object[] { new[]{"param1", "param2"} });

Remember that Invoke doesn't accept a single value of that one parameter either. It accepts an array of all parameters. Passing new string[] { "param1", "param2" } to Invoke is telling Invoke that you have two parameters, each of which are strings. You need to wrap your one array parameter in another array so that Invoke sees that you have one parameter that is itself an array.

نصائح أخرى

Try this: method.Invoke(obj, new object[] {new string[] {"param1", "param2"}});

.Invoke takes an array of arguments that represents the entire signature. in your case the first argument should be an array of strings. So you have to pass in an array of objects with the first element being the array of strings.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top