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

本文介绍如何仅使用Mono嵌入API来调用C#泛型方法,而不需要在程序集中添加辅助方法。通过反射获取泛型方法的实例,并利用Mono API中的 MethodInfo.MakeGenericMethod 方法进行泛型参数的指定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值