I'm using reflection to call a generic method with a type determined at runtime. My code is as follows:
Type tType = Type.GetType(pLoadOut.Type);
MethodInfo method = typeof(ApiSerialiseHelper).GetMethod("Deserialise", new Type[] { typeof(string) });
MethodInfo generic = method.MakeGenericMethod(tType);
generic.Invoke(obj, new object[] { pLoadOut.Data });
This works ok. However the generic.Invoke method returns an object, but what I would like is the type determined at runtime. Is this possible with this approach, or is there a better option?
Mark
The type IS determined at runtime. It's the type of the reference variable that is object, the actual instance is strongly typed.
That's the best that can be done, considering that you're using reflection to dynamically get access to a method that the compiler has no type information for -- it might not even exist in the build environment.
EDIT: If you know something about the type returned by Deserialize
, then you can take advantage of delegate variance. For example:
Type tType = Type.GetType(pLoadOut.Type);
MethodInfo method = typeof(ApiSerialiseHelper).GetMethod("Deserialise", new Type[] { typeof(string) });
MethodInfo generic = method.MakeGenericMethod(tType);
Converter<string,ISomething> deser = (Converter<string,ISomething>)Delegate.CreateDelegate(typeof(Converter<string,ISomething>),generic);
ISomething result = deser(pLoadOut.Data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With