Embedded Mono: Invoking a C# generic method (Part 2)

Embedded Mono: Invoking a C# generic method (Part 2)

A while ago I wrote about how to invoke a C# generic method, by using a helper method in the assembly. In this post, we will see how to invoke generic methods using solely the Mono embedding API. A much preferred alternative, since you don’t pollute your assemblies with helper methods that are used by C++ only.

As before, the TestClass that contains the generic method:

As is the previous post, we will still use reflection to get a specialized instance of GenericMethod, but this time we will do it solely through the embedding API.

The first step is to find the MethodInfo.MakeGenericMethod method:

Then, we want to find the TestClass.GenericMethod and get an instance of a MonoReflectionMethod, that represents the GenericMethod. On that instance, we will later call the makeGenericMethod MonoMethod that we got from above.

The MethodInfo.MakeGenericMethod method accepts an array of Types as its only parameter. Lets create that array:

Now we have have everything we need to call the MakeGenericMethod; a method definition, an instance to call it against and the method parameters:

We now have a MethodInfo instance, that represents the voidGenericMethod(String t) method. What we need now, is the value of its MethodHandle property:

All that is left to do is to unbox the methodHandle into a MonoMethod and invoke the latter as usual:

That’s all for this tutorial. Full source code can be found here.

猜你喜欢

转载自blog.csdn.net/linuxheik/article/details/80320178