我试图给出一个我不知道类的构造函数的类型的列表。
首先,我有一个包含多个表和方法的类:
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));
}
}
}
}
我想要实现的通用类:
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;
}
}
问题是这一行: confContainer.ConfEntries [i] = new ConfEntryList(property.Name,property.GetValue(this,null));
我不知道如何将List类型传递给构造函数:
new ConfEntryList<T>(...)
是否可以将类型T(由PropertyInfo捕获的任何通用列表)传递给通用构造函数?
提前感谢您提供任何帮助
答案 0 :(得分:2)
像这样......
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;
}