Constructor mapping to mapping in a generic type definition

I thought about this problem for a while, and it seems to me that there should be a simple solution that I am 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 of type Foo<System.Int32> , I will return to two constructors, as with one parameter of type System.Int32 , which cannot be differentiated.

If I get all the constructors from the type definition of Foo<System.Int32> ( Foo<T> ), I will return two constructors. One that 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 map the constructor to its counterpart in defining a generic type?

+6
source share
1 answer

To compare ctors in both cases, you can compare their MetadataToken. Example:

 foreach (var item in ctors1) { var ctorMatch = ctors2.SingleOrDefault(c => c.MetadataToken == item.MetadataToken); } 
+2
source

Source: https://habr.com/ru/post/974664/


All Articles