0
void A(object o) { ... Assembly a = Assembly.LoadFile(...); Type t = a.GetType(@"namespace.className"); MethodInfo mi = t.GetMethod(@"MethodName"); mi.Invoke(instace, new Object[] {o}); .... } 

the method I need to invoke accept another type, I need to cast the object to that type, but, the type is known only at run time, so can I convert/cast object to another type known only at run time ? I can change only method A.

thank you.

1
  • Are you trying to invoke a specific overload of MethodName? That's the only reason I can think of to need the argument type. Commented Mar 9, 2015 at 13:40

4 Answers 4

1

The Reflection APIs only deal with object references. Casting a reference is an operation on that reference. It does not affect the object in any way.

For that reason it is not necessary to cast anything here. Just pass o to Invoke like you are already doing. The Reflection API validates the type of o and passes it to the method you want to call.

Sign up to request clarification or add additional context in comments.

Comments

1

The MethodInfo.Invoke(object instance, object[] arguments) is dynamic invoke. That means, the casting is made automatically. If is thrown InvalidCastException, then you pass the wrong argument or the exception is thrown from inner code and is not caused by object passed to arguments.

Comments

0

This is the code I used when I had several similar messages coming need, that needed different handling. Ordertype was a Type instance of a custom order object.

 var _ot = Activator.CreateInstance(ordertype); var _otconvert = ordertype.GetMethod("ConvertRequestPayload"); object[] _params = new object[] {message}; var objectf = _otconvert.Invoke(_ot, _params); var _as = Activator.CreateInstance(servicetype); var _method = servicetype.GetMethod("StartProcess"); var rMessage = _method.Invoke(_as, new object[] {objectf}); 

Basically Activator is what you need. it allows you create objects of required type at runtime.

2 Comments

I don't want to create another instance ... I want to use {This} instance.
I don't think what you trying to accomplish is possible with using the instance you already have, especially if you want to cast or convert it. If I am wrong then i'll learn something new as well.
0

I changed {object 0}to {dynamic 0} and it worked.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.