I have a generic class MyList<T> : MyBaseClass, IList<T>
which accepts an unknown amount of unknown element types.
Somewhere else I declare some custom lists BUT without instantiating them (it is a must due to some general restrictions):
MyList<MyObjectType1> type1List1, type1List2,... ;
MyList<MyObjectType2> type2List1, type2List2,... ;
I would like to instantiate those custom lists at runtime using reflection:
foreach (FieldInfo field in this.GetType().GetFields())
{
if (field.FieldType == typeof(MyList<>)) // this condition is **NEVER** passed!
{
MyList<>valueToSet = new MyList<>(); // does not work, needs type
MyList<T>valueToSet = new MyList<T>(); // does not work, there's no T
MyList<...?...>valueToSet = new MyList<...?...>(); // how can i put here the type?
field.SetValue(this, valueToSet);
...
}
}
The problems I encountered are that, thus the type of the objects used in each of the declared lists is unknown untill runtime, I can not find an expression to use in my code for the instantiation MyList<...?...>valueToSet = new MyList<...?...>()
, as well as that surprisingly (at least for me) the expression if (field.FieldType == typeof(MyList<>))
never passes.
Just in case suggested please be aware that, due to some class dependencies and constraints I can not create an interface for MyList<T>
.
Thanks in advance for any help!
Aucun commentaire:
Enregistrer un commentaire