简体   繁体   中英

C# generic list as constructor parameter

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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