I'm attempting to deserialize a Generic<T> where T : struct
but when I call ctor.Invoke(args);
I get the exception "Cannot create an instance because Type.ContainsGenericParameters is true".
How do I pass the generic type I want it to be?
Let's say you have a Type t
of a generic class which has a parameter-less constructor, and an array of the types to use as the type parameters of the generic class:
Type t = someType;
Type[] genericTypeParameters = someArrayOfTypeParameters;
Call Type.MakeGenericType()
, which
Substitutes the elements of an array of types for the type parameters of the current generic type definition and returns a Type object representing the resulting... type
Then construct the object as normal:
t = t.MakeGenericType(genericTypeParameters);
object instance = Activator.CreateInstance(t);
Type.MakeGenericType
is probably what you are looking for...
You have to create a concrete type first using the MakeGenericType method on your generic type
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