繁体   English   中英

C#通用列表作为构造函数参数

[英]C# generic list as constructor parameter

我试图给一个类的构造函数提供一个我不知道类型的列表。

首先,我有一个包含多个表和一个方法的类:

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] =新的ConfEntryList(property.Name,property.GetValue(this,null));

我不知道如何将List类型传递给构造函数:

new ConfEntryList<T>(...)

是否可以将类型T(由PropertyInfo捕获的任何通用列表)传递给通用构造函数?

预先感谢您的任何帮助

您需要使用Activator.CreateInstance

像这样

       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;
       }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM