【问题标题】:C# generic list as constructor parameterC# 泛型列表作为构造函数参数
【发布时间】:2015-03-09 11:56:46
【问题描述】:

我正在尝试将我不知道类型的列表提供给类的构造函数。

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

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 捕获的任何泛型列表的)传递给泛型构造函数?

提前感谢您的帮助

【问题讨论】:

    标签: c# list class generics types


    【解决方案1】:

    你需要使用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;
           }
    

    【讨论】:

    • 感谢您的回答,我已经尝试过制作类似的东西,但我遇到了同样的问题:confContainer.ConfEntries [i] = item;返回编译器错误:无法将类型 'object' 隐式转换为 'ConfEntry' 并且我无法转换项目,因为我需要列表类型来执行此操作:confContainer.ConfEntries [i] = (ConfEntryList) item;跨度>
    • 您还没有发布 ConfContainer 的代码,所以我看不出 ConfEntries 属性是什么类型,ConfContainer 类似乎不是通用的,所以我假设 ConfEntries 是一个 List 在哪种情况下转换为 ConfEntry 应该没问题。
    • 您的 ConfEntries 只是一个 ConfEntry 数组,因此投射到 ConfEntry 就可以了,因为您的 ConfEntryList 可以从中得到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多