lundi 24 janvier 2022

How to use a Type variable to cast an object or instantiate a generic class? [duplicate]

Is it possible to do the following in C#?

Type myType = typeof(string);
var s1 = new List<myType>(); //s1 would be List<string>
var s2 = (myType) getObject(); //s2 would be string 

I've tried a bunch of ways but they all end up either eventually requiring T (for var myVar = (T) getObject(); or new List<T>(). I'm trying to do this without having any T. Only having the type info in a Type variable.





Aucun commentaire:

Enregistrer un commentaire