With 'ConstructorInfo' from a built generic type, how do I get a match to 'ConstructorInfo' from a public type?
In .NET, I have an instance ConstructorInfo
. A declaration type is a built generic type (aka foo.DeclaringType.IsConstructedGenericType == true
). I want to get an instance ConstructorInfo
that belongs to the public type i.e. Typical definition of an ad type.
Get the open type itself directly with foo.DeclaringType.GetGenericTypeDefinition()
; however, there is currently no obvious way to get the match constructor. I can list all the constructors on both sides, but then I still run into the problem of matching these two lists; and I'm not sure if .NET provides any guarantees that the constructors will be listed in the same order.
Does anyone have a way to get the original copy ConstructorInfo
?
source to share
I think you can match constructors using a property MetadataToken
:
var closed = foo.GetType().GetConstructors().Select(c => c.MetadataToken);
var open = foo.GetType().GetGenericTypeDefinition().GetConstructors().Select(o => o.MetadataToken);
var b = Enumerable.SequenceEqual(closed, open); //returns true
It seems that the private and public version of the constructors have the same metadata token, so this would be a way to connect both lists. This persists even if the generic class and the private type are defined in different assemblies.
I have not found anything that confirms this as documented behavior, but you should be able to investigate further in ECMA C # and the Standard Language Infrastructure Standards or ECMA-335 Standard - Common Language Infrastructure (CLI)
source to share