C# 如何将未知类型的泛型列表传递给类构造函数

C# 如何将未知类型的泛型列表传递给类构造函数,c#,C#,下面的代码片段对于给定的方法来说效果很好,但我想在类构造期间也这样做。怎么做 public static DataTable ToDataTable<T>(IList<T> data) 公共静态数据表到数据表(IList数据) 想要这样的东西…但是构造函数不喜欢(IList部分 public class DTloader { PropertyDescriptorCollection props; DataTable dataTable = new Da

下面的代码片段对于给定的方法来说效果很好,但我想在类构造期间也这样做。怎么做

public static DataTable ToDataTable<T>(IList<T> data)
公共静态数据表到数据表(IList数据)
想要这样的东西…但是构造函数不喜欢
(IList
部分

public class DTloader
{
    PropertyDescriptorCollection props;
    DataTable dataTable = new DataTable();
    public DTloader<T>(IList<T> data)
    {
        props = TypeDescriptor.GetProperties(typeof(T));
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            dataTable.Columns.Add(prop.Name, prop.PropertyType);
        }
    }
公共类DTloader
{
PropertyDescriptorCollection道具;
DataTable=新的DataTable();
公共DTloader(IList数据)
{
props=TypeDescriptor.GetProperties(typeof(T));
for(int i=0;i
….

在这一点上,类本身需要是泛型的。如下所示:

public class DTloader<T>
{
    //...

    public DTloader(IList<T> data)
    {
        //...
    }
}
公共类DTloader
{
//...
公共DTloader(IList数据)
{
//...
}
}

构造函数在编译时会知道什么是
T
,因为类实例的声明会指定它(或能够推断它)。

除了给出的答案之外,如果您想要一个非泛型DTLoader,您可以创建一个抽象DTLoader,并使泛型DTLoader从中继承

abstract class DTLoader
{
 //..
}

class DTLoader<T> : DTLoader
{
   public DTloader(IList<T> data)
   {
    //...
   }
}
抽象类DTLoader
{
//..
}
类DTLoader:DTLoader
{
公共DTloader(IList数据)
{
//...
}
}

这实际上会给你一种你想要的感觉——让构造函数使用泛型类型。

这看起来与你的问题类似:有趣——感谢你扩展了我的理解!