How to treat type two T as equal if they have the same constraints?
Let's assume I have two general methods:
static void Foo<T>(T argument) { }
static void Bar<T>(T argument) { }
The following code returns false because the two T
are of different types and may have different constraints:
var flags = BindingFlags.Static | BindingFlags.NonPublic;
var foo = typeof (Program).GetMethod("Foo", flags)bar.GetParameters()[0];
var bar = typeof(Program).GetMethod("Bar", flags)foo.GetParameters()[0];
bool test = foo.ParameterType == bar.ParameterType; // false
I would like to write a method that compares two T
based on their constraints and returns true if they have the same constraints. For example, the above result must be true since both parameters have no restriction.
I can use the method GetGenericParameterConstraints
and compare the types, but I also want to check for class
, struct
and new()
. Is there a way to do this using Reflection
?
source to share
Look at the property of GenericParameterAttributes
your instances foo.ParameterType
and bar.ParameterType
: it returns an enum that contains all the possible attributes for your type.
You will be interested in:
-
ReferenceTypeConstraint
(if you addedclass
as constraint) -
NotNullableValueTypeConstraint
(if you addedstruct
as constraint) -
DefaultConstructorConstraint
(if not combined withNotNullableValueTypeConstraint
, you addednew()
as constraint)
source to share
You can use this method if the order of the parameters is important:
private static bool CompareGenerics(MethodInfo m1, MethodInfo m2)
{
var args1 = m1.GetGenericArguments();
var args2 = m2.GetGenericArguments();
if (args1.Length != args2.Length)
return false;
for (int i = 0; i < args1.Length; i++)
{
if ((args1[i].GenericParameterAttributes ^ args2[i].GenericParameterAttributes) != 0)
return false;
}
return true;
}
source to share