C# : How to call dynamically a generic methodFiled Under: c#
Recently, I encountered a problem in C#. I had to invoke a generic method but didn’t know which object would be in entry because I was going to seek it through reflection.
So, I have a method that could be called, for example:
public bool MyMethod<T>(T x, Tx)
I want to call it but I do not know what is T. T may be several different things depending on the rest of the code. I cannot affect T with anythings. The compiler will not accept, for example:
bool resultat = MyMethod<this.getType()>(x,y)
After some research on google, I changed the code snippets that I found and it gave me this:
private object invokeGenericMethod(string typeName,string methodName,object[] parameters) { Type type = System.Type.GetType(typeName); MethodInfo method = this.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance); MethodInfo genericMethod = method.MakeGenericMethod(type); return genericMethod.Invoke(this, parameters); }
So, to invoke dynamically, I can now have something like:
object[] invokeArgs = { "parameter1","parameter2","etc" }; object result = InvokeGenericMethod(this.GetType().Name, "MyMethod", invokeArgs);
I use the first parameter of InvokeGenericMethod to pass the type of class. So the code will always be adapted from the class from which it is called.
Tags: c#
- Permalien
- guroot
- 09:53 AM
- Comments(0)