Given an object of type System.Reflection.MethodInfo
how can I extract generic parameter constraints? Somehow I can not find reasonable information about this.
All you need to do is grab the generic method definition, and list the generic arguments on that:
method
.GetGenericMethodDefinition()
.GetGenericArguments()
.Select(i => i.GetGenericParameterConstraints())
.Dump();
However, note that this doesn't 100% correspond to C#'s generic type constrains - there's a bit of wiggle room. Still, if you only care about e.g. a base-type constraint, it will work fine :)
As an example, class
isn't actually a type constraint at all, interestingly, while struct
is "translated" as System.ValueType
(not too surprising). new()
isn't a type constraint either, so this method doesn't work to find that.
If you need to take those constraints into account as well, use the GenericParameterAttributes
property in the Select
. For example, struct
constraint will give you NotNullableValueTypeConstraint | DefaultConstructorConstraint
.
GetGenericMethodDefinition
call. If in doubt, ask yourself - can I invoke this method (or instantiate a type)? If the answer is yes, your method (or type) is reified, and you'll need to get the generic-er method (or type). –
Definition You are probably looking for Type.GetGenericParameterConstraints Method ()
Returns an array of Type objects that represent the constraints on the current generic type parameter.
Also 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
© 2022 - 2024 — McMap. All rights reserved.