mercredi 5 avril 2017

Ignoring constraints when creating open generic type using reflection

I work on a code that compares structures of classes in C# as a part of a serialization library.

I stumbled upon a problem with the particular generic class setup:

class B<Y> where Y: B<Y> {}
class A<X>: B<A<X>> {}

I already have objects of type Type that represents open generic type B<> and open generic type A<>. Now I would like to create open generic type B<A<>> that I will use as a template for other closed generic types. In order to do that I tried using MakeGenericType method:

typeof(B<>).MakeGenericType(typeof(A<>))

but it ended up with an exception about "Invalid generic arguments". It makes sense as type A<> does not meet a constraint of Y generic argument.

I know that I can obtain the type I want by calling typeof(A<>).BaseType, but it does not fit the flow of my algorithm and seems not to be a general solution to the problem. My question is: is there a way to create an open type B<A<>> ignoring/deferring constraint check to the moment of creating a closed version of it?





Aucun commentaire:

Enregistrer un commentaire