首页 > 解决方案 > 如何使用 Type.GetMethod(string name, int genericParameterCount, Type[] types) 获取通用 MethodInfo?

问题描述

我正在尝试获取MethodInfo特定方法Interlocked.CompareExchange<T>(ref T, T, T)并尝试以下代码无济于事:

typeof(Interlocked).GetMethod(nameof(Interlocked.CompareExchange), 1, new Type[] { typeof(int), typeof(int), typeof(int) })

请注意,这typeof(int)只是一种随机类型。我所需要的只是MethodInfo这样我以后可以使用GetGenericMethodDefinition不同的类型。

我们应该传递什么类型的数组来获取所需的方法?

标签: c#.net-standard-2.1

解决方案


解决方案非常简单:

Type genericType = Type.MakeGenericMethodParameter(0);
Type[] types = new Type[] { genericType.MakeByRefType(), genericType, genericType };

MethodInfo methodInfo = typeof(Interlocked).GetMethod(nameof(Interlocked.CompareExchange), 1, types);

推荐阅读