Reputation: 353
I am trying to give a list which I don't know the type to a constructor of a class.
First I have a class which contains multiples tables and a method:
public class A{
private List<float> _List1;
private List<Proj> _List2;
...
public void saveConfig(string path){
ConfContainer confContainer = new ConfContainer ();
Type type = this.GetType();
PropertyInfo[] properties = type.GetProperties();
confContainer.ConfEntries = new ConfEntry[properties.Length];
int i = 0;
foreach (PropertyInfo property in properties){
if(property.GetValue(this,null) is IList && property.GetValue(this,null).GetType().IsGenericType){
confContainer.ConfEntries [i] = new ConfEntryList (property.Name, property.GetValue(this, null));
}
}
}
}
And the generic class I am trying to achieve:
public class ConfEntryList<T>: ConfEntry{
[XmlArray("Valeurs")]
[XmlArrayItem("Valeur")]
public List<T> Valeurs;
public ConfEntryList(){
}
public ConfEntryList(string attribut, List<T> valeurs){
this.Attribut = attribut;
this.Valeur = null;
this.Valeurs = valeurs;
}
}
The problem is this line: confContainer.ConfEntries [i] = new ConfEntryList (property.Name, property.GetValue(this, null));
I don't know how to pass the List type to the constructor:
new ConfEntryList<T>(...)
Is it possible to pass the type T (of any generic list captured by PropertyInfo) to a generic constructor?
Thanks in advance for any help
Upvotes: 1
Views: 1680
Reputation: 16018
You need to use Activator.CreateInstance
Something like this..
if(property.GetValue(this,null) is IList
&& property.GetValue(this,null).GetType().IsGenericType){
var listType = property.PropertyType.GetGenericArguments()[0];
var confType = typeof(ConfEntryList<>).MakeGenericType(listType);
var item = (ConfEntry)Activator.CreateInstance(confType,
new object [] {property.Name, property.GetValue(this, null)});
confContainer.ConfEntries [i] = item;
}
Upvotes: 2