在编译时不知道类型就创建IEnumerable []

时间:2016-06-28 14:28:34

标签: c#

我遇到的情况是我必须在编译时不知道类型的情况下创建实例。

我的代码是这样的:

     IEnumerable[] columns = new IEnumerable[5]; 

     columns[0] = new string[]{};

我必须能够在不知道类型的情况下创建colums [0](在上例中是字符串)。

我无法找到问题的解决方案,欢迎任何建议。

提前谢谢。

2 个答案:

答案 0 :(得分:0)

你可以使用这样的泛型:

class MyBusiness<T> where T: new()
{
    public List<T> coll { get; set; }

    public MyBusiness(){
        coll = new List<T>();
    }

    public void DoSth(){
        T t = new T();
        coll.Add(t);
    }
}

答案 1 :(得分:0)

您需要查看Generics。它们允许您创建一个类,在您使用它之前不需要知道类型是什么。

public class Column<T>
{
    public T Item { get; set; }
}

所以你在你的程序中使用它是这样的:

var columns = new IEnumerable<Column<string>>();
相关问题