Generic call method using runtime type and return object

I use reflection to call a generic method with a type defined 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 is working fine. However, the generic.Invoke method returns an object, but what I would like is the type defined at runtime. Is this possible with this approach or is there a better option?

Mark

+5
source share
2 answers

Type IS is determined at runtime. This is the type of the reference variable that is the object; the actual instance is strongly typed.

, , , , - .

EDIT: - , Deserialize, . :

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);
+5

, . , , , DoSomething(), , DoSomething().

0

All Articles