I have been thinking about this problem for a while and it feels like there must be a simple solution that I'm missing.
Let's say I have the following class:
public class Foo<T>
{
public Foo(T value)
{
}
public Foo(int value)
{
}
}
If I get all constructors on the type Foo<System.Int32>
I will get back two constructors, both with a single parameter of type System.Int32
which cannot be differentiated.
If I get all constructors from the generic type definition of Foo<System.Int32>
(Foo<T>
) I will get back two constructors. One which accepts a generic parameter T
and one that accepts a parameter of type System.Int32
// Will return two constructors with signatures that look identical.
var type = typeof(Foo<int>);
var ctors1 = type.GetConstructors();
// Will return two constructors as well. Parameters can be differentiated.
var genericTypeDefinition = typeof(Foo<int>).GetGenericTypeDefinition();
var ctors2 = genericTypeDefinition.GetConstructors();
Is there a way to match a constructor to its counterpart in its generic type definition?
For Comparing the ctors
in both cases you can compare their MetadataToken.
Example:
foreach (var item in ctors1)
{
var ctorMatch = ctors2.SingleOrDefault(c => c.MetadataToken == item.MetadataToken);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With