Consider this code sample from a WinForms app:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
object[] parms = new object[1];
parms[0] = "foo";
DoSomething(parms);
}
public static string DoSomething(object[] parms)
{
Console.WriteLine("Something good happened");
return null;
}
}
It works as expected, when you click button1 it prints "Something good happened" to the console.
Now consider this code sample, which is the same except that it invokes DoSomething using reflection:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
object[] parms = new object[1];
parms[0] = "foo";
System.Reflection.MethodInfo mi = typeof(Form1).GetMethod("DoSomething");
mi.Invoke(null, parms);
}
public static string DoSomething(object[] parms)
{
Console.WriteLine("Something good happened");
return null;
}
}
It throws an System.ArgumentException on the line mi.Invoke(null, parms) (Object of type 'System.String' cannot be converted to type 'System.Object[]'.)
parms is clearly an object array, and DoSomething's method signature is clearly expecting an object array. So why is invoke pulling the first object out of the array and trying to pass that instead?
Or is something else going on that I'm not understanding?
MethodInfo.Invoke is expecting an object array, where each object in the object array corresponds to an argument to the method. The first argument in the object array is the first argument, the second object in the array the second method, etc.
Since you want the first argument to your method to be an object[], you need to ensure that the first object in the object array you pass to MethodInfo.Invoke is an object array that represents the array that DoSomething should use.
object[] parms = new object[1];
parms[0] = "foo";
with:
public static string DoSomething(object[] parms)
that's the problem; the first parameter is not a string - it is an object[]. The object[] that you pass to Invoke represents each parameter in turn, so an object[] of length 1 with a string would match static string DoSomething(string s), but does not match your method. Either change the signature, or wrap the value. Frankly, I suggest changing the signature is the better idea here, but:
parms[0] = new object[] { "foo" };
would also work
MethodInfo.Invoke expects an array of objects as parameter to pass multiple arguments to the functions, each object in the array will be a different parameter.
As your function also expects an object array you are passing as argument not an object array but an string.
You must wrap that array into another array, in this way the Invoke will unwrap the first array and use the inner array as the first parameter for the call.
mi.Invoke(null, new object[]{ parms });
parms is clearly an object array, and DoSomething's method signature is clearly expecting an object array.
Yes it is expecting an object array. But when you pass this:
object[] parms = new object[1];
You are saying these are the arguments for DoSomething so parms[0] is the first argument to DoSomething and if there were more items in parms then parms[1] will be the 2nd argument and so on.
Clearly the first argument for DoSomething is not a string (parms[0]) so you get this error:
It throws an System.ArgumentException on the line mi.Invoke(null, parms) (Object of type 'System.String' cannot be converted to type 'System.Object[]'.)
Related
In order to change a control by another thread, I need to invoke a delegate to change the control However, it is throwing a TargetParameterCountException:
private void MethodParamIsObjectArray(object[] o) {}
private void MethodParamIsIntArray(int[] o) {}
private void button1_Click(object sender, EventArgs e)
{
// This will throw a System.Reflection.TargetParameterCountException exception
Invoke(new Action<object[]>(MethodParamIsObjectArray), new object[] { });
// It works
Invoke(new Action<int[]>(MethodParamIsIntArray), new int[] { });
}
Why does invoking with MethodParamIsObjectArray throw an exception?
This is due to the fact that the Invoke method has a signature of:
object Invoke(Delegate method, params object[] args)
The params keyword in front of the args parameter indicates that this method can take a variable number of objects as parameters. When you supply an array of objects, it is functionally equivalent to passing multiple comma-separated objects. The following two lines are functionally equivalent:
Invoke(new Action<object[]>(MethodParamIsObjectArray), new object[] { 3, "test" });
Invoke(new Action<object[]>(MethodParamIsObjectArray), 3, "test");
The proper way to pass an object array into Invoke would be to cast the array to type Object:
Invoke(new Action<object[]>(MethodParamIsObjectArray), (object)new object[] { 3, "test" });
Invoke expects an array of objects containing the parameter values.
In the first call, you aren't providing any values. You need one value, which confusingly needs to be an object array itself.
new object[] { new object[] { } }
In the second case, you need an array of objects containing an array of integers.
new object[] { new int[] { } }
I have a class which contains an empty constructor and one that accepts an array of objects as its only parameter. Something like...
public myClass(){ return; }
public myClass(object[] aObj){ return; }
This is the CreateInstance() method call that I use
object[] objectArray = new object[5];
// Populate objectArray variable
Activator.CreateInstance(typeof(myClass), objectArray);
it throws System.MissingMethodException with an added message that reads
"Constructor on type 'myClass' not found"
The bit of research that I have done has always shown the method as being called
Activator.CreateInstance(typeof(myClass), arg1, arg2);
Where arg1 and arg2 are types (string, int, bool) and not generic objects.
How would I call this method with only the array of objects as its parameter list?
Note: I have tried adding another variable to the method signature. Something like...
public myClass(object[] aObj, bool notUsed){ return; }
and with this the code executed fine.
I have also seen methods using reflection which were appropriate but I am particularly interested in this specific case. Why is this exception raised if the method signature does in fact match the passed parameters?
Cast it to object:
Activator.CreateInstance(yourType, (object) yourArray);
Let's say you have constructor:
class YourType {
public YourType(int[] numbers) {
...
}
}
I believe you would activate like so by nesting your array, the intended parameter, as a item of the params array:
int[] yourArray = new int[] { 1, 2, 4 };
Activator.CreateInstance(typeof(YourType ), new object[] { yourArray });
Is it possible in C# to accept a params argument, then pass it as params list to another function? As it stands, the function below will pass args as a single argument that is an array of type object, if I'm not mistaken. The goal here is self evident.
//ScriptEngine
public object[] Call(string fnName, params object[] args)
{
try{
return lua.GetFunction(fnName).Call(args);
}
catch (Exception ex)
{
Util.Log(LogManager.LogLevel.Error, "Call to Lua failed: "+ex.Message);
}
return null;
}
The lua.GetFunction(fnName).Call(args); is a call to outside of my code, it accepts param object[].
If the signature of the Call method you're calling accepts a params object[] args then you are mistaken. It doesn't consider args a single object of thpe object, to be wrapped in another array. It considers it the entire argument list, which is what you want. It'll work just fine exactly as it stands.
Yes, it is possible.In your case args actualy an array of objects.Your Call method should take params object[] or just an array of objects as parameter.
You don't need to pass more than one argument to params.You can pass an array directly.For example this is completely valid:
public void SomeMethod(params int[] args) { ... }
SomeMethod(new [] { 1, 2, 3 });
It is possible to pass the array to another function:
void Main()
{
int[] input = new int[] {1,2,3};
first(input); //Prints 3
}
public void first(params int[] args)
{
second(args);
}
public void second(params int[] args)
{
Console.WriteLine(args.Length);
}
I am trying to instantiate a type using Activator's reflection magic. Unfortunately the type I want to instantiate has a params parameter of type object. See this extract:
public class Foo
{
public Foo(string name, params object[] arguments)
{
}
}
And the instantiation goes here:
public static class Bar
{
public static object Create(params object[] arguments)
{
return Activator.CreateInstance(typeof(Foo), "foo", arguments);
}
}
Now, this effectively results in a constructor call with the signature
new Foo(string, object[])
because object[] is also object.
What I actually want is:
new Foo(string, object, object, object, ...)
Is this even possible with Activator? Or how do I instantiate a type with such a parameter type?
params is a purely-compile-time syntactic sugar.
The runtime, including the parameter binding used by reflection, ignores it.
You need to pass a normal array, just like a non-params parameter.
In your case, it sounds like you're trying to not call the params overload.
You need to build a single (flattened) array containing all of the parameters you want to pass:
object[] args = new object[arguments.Length + 1];
args[0] = "foo";
arguments.CopyTo(args, 1);
You can pass parameters like this:
return Activator.CreateInstance(
typeof(Foo),
new object[] { "foo" }.Concat(arguments).ToArray());
I have this class:
using System.Linq;
namespace TestNamespace {
public class Program {
public static void Main(string[] args) {
//does stuff
}
}
}
I am loading the above assembly and want to invoke the method with a string array parameter.
This gives me a null exception:
private static object[] parameters = new object[1];
string[] pa = { "1", "2" };
parameters[0] = pa;
//Creating target and other code
bool retVal = (bool)target.Invoke(null, parameters);
Any thoughts? Thanks
Where's the NullReferenceException. Are you sure that you're reflecting the MethodInfo correctly and that target is not null? That's my suspicion as to what's really going on here. If there were a NullReferenceException being thrown in the method, it would be wrapped in a TargetInvocationException and thus I suspect the NullReferenceException is because target is null.
To be clear, here's how you load and invoke the method:
var target = typeof(Program)
.GetMethod("Main", BindingFlags.Public | BindingFlags.Static);
bool retVal = (bool)target.Invoke(null, new object[] { pa });
The parameters parameter to MethodInfo.Invoke is an object[] with the same number, order and types of the parameters for the method being invoked. In your case, you have a single parameter of type string[]. Thus, the object[] parameter to MethodInfo.Invoke should be an array with one element, and that element is an instance of string[]. That is what I have accomplished with the syntax above.