简体   繁体   English

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

[英]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)); 问题是这一行:confContainer.ConfEntries [i] =新的ConfEntryList(property.Name,property.GetValue(this,null));

I don't know how to pass the List type to the constructor: 我不知道如何将List类型传递给构造函数:

new ConfEntryList<T>(...)

Is it possible to pass the type T (of any generic list captured by PropertyInfo) to a generic constructor? 是否可以将类型T(由PropertyInfo捕获的任何通用列表)传递给通用构造函数?

Thanks in advance for any help 预先感谢您的任何帮助

You need to use Activator.CreateInstance 您需要使用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;
       }

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

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