How does one cast the return value from CreateInstance when the type is unknown?
For example in this code:
MethodInfo mInfo = typeof(MyType).GetMethod(MethodBase.GetCurrentMethod开发者_如何学Go().Name);
Object o = Activator.CreateInstance(mInfo.ReturnType);
how do I cast my o to whatever mInfo.ReturnType contains?
Casting (at least, in the way you usually mean) is a compile-time / static-typed operation. The only way that even makes sense at runtime with an unknown type is when dealing either with generics (casting it to some T
- and note that you can choose the T
at runtime via MakeGenericMethod
or MakeGenericType
), or with meta-programming (emitting IL to do the appropriate cast). In all other cases when the type is unknown until runtime, you are stuck with either object
or dynamic
.
Commonly you cant do it in habitual manner, except situations mInfo.ReturnType
contains definition of type which is visible in current context at compile time. For example if mInfo.ReturnType
have bool
definition you can simply do:
bool t = (bool)o;
But in this case there is no sence to use Activator. Activator class is used when you try to use type which was load from another assembly in other word the type is not visible at compile time.
So the answer you have no way to do this.
精彩评论