Cast value's in object[] to type based on result from method.GetParameters

Basically I am trying to .Invoke a method, I have a list of parameters however the list contains objects of the wrong type. I would like to be able to do something like this:
public void MethodExpectingInt(int value);


MethodInfo = GetType().GetMethod("MethodExpectingInt");
object[] args = { new IntWrapper(42); }
method.Invoke(this, args);
public void MethodExpectingInt(int value);


MethodInfo = GetType().GetMethod("MethodExpectingInt");
object[] args = { new IntWrapper(42); }
method.Invoke(this, args);
I tried implementing implicit operator int, as well as using Convert.ChangeType, however neither have worked
3 Replies
Thinker
Thinker2d ago
Convert.ChangeType will almost never do what you actually want fyi You can't really do this kind of conversion automatically, you have to invoke the method with the exact parameters specified. What you could do is just get the int from the IntWrapper instead of passing the wrapper directly ... what are you using the wrapper for anyway?
Strikeeaglechase
StrikeeaglechaseOP2d ago
In the actual code it basically is a situation where a user can decide to provide a constant int, or a "GlobalVariable", which I want to evaulate at the time invoke is called, which is what IntWrapper is representing here I was hoping for a generic solution as the code here is used for a lot of different methods with different signatures, and sometimes the value would be a raw int and sometimes would be wrapped Ultimately just checking if each paramater is an instance of intwrapper and if it is getting the internal value will be probably what im left with, but I was hoping for something a bit more generic
Thinker
Thinker2d ago
You could have something like an IWrapper interface with a single object Inner { get; } property, then you can check whether an object is an IWrapper and then get the inner value.

Did you find this page helpful?