如何通过 C# 中的反射提取泛型方法约束?

How to extract generic method constraints via reflection in C#?

给定一个 System.Reflection.MethodInfo 类型的对象,我如何提取通用参数约束?不知何故,我找不到关于此的合理信息。

您可能正在寻找 Type.GetGenericParameterConstraints Method ()

Returns an array of Type objects that represent the constraints on the current generic type parameter.

还有Type.GetGenericArguments Method ()

Returns an array of Type objects that represent the type arguments of a closed generic type or the type parameters of a generic type definition

您需要做的就是获取通用方法定义,并列出通用参数:

method
.GetGenericMethodDefinition()
.GetGenericArguments()
.Select(i => i.GetGenericParameterConstraints())
.Dump();

但是,请注意,这并非 100% 对应于 C# 的泛型类型约束 - 存在一些回旋余地。不过,如果您只关心例如基本类型约束,它将正常工作:)

例如,有趣的是,class 实际上根本不是类型约束,而 struct 是 "translated" 和 System.ValueType(不足为奇)。 new() 也不是类型约束,因此此方法无法找到它。

如果您还需要考虑这些限制,请使用 Select 中的 GenericParameterAttributes 属性。例如,struct 约束会给你 NotNullableValueTypeConstraint | DefaultConstructorConstraint.