2017-07-17 66 views
1

下面的代码段对于给定的方法工作得很好,但我希望在类构造期间执行相同的操作。怎么做?如何将未知类型的通用列表传递给类构造函数

public static DataTable ToDataTable<T>(IList<T> data) 

想要这样的东西...但构造函数不喜欢<T>(IList<T>部分。

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

.......

+1

这看起来类似于你的问题:https://stackoverflow.com/questions/39196357/generic-class-with-generic-constructor – SchwiftyPython

回答

5

此时类本身将需要通用的。事情是这样的:

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

    public DTloader(IList<T> data) 
    { 
     //... 
    } 
} 

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

1

除了给出答案,如果你想拥有一个非一般的DTLoader你可以创建一个抽象DTLoader,使通用的一个从它继承

abstract class DTLoader 
{ 
//.. 
} 

class DTLoader<T> : DTLoader 
{ 
    public DTloader(IList<T> data) 
    { 
    //... 
    } 
} 

这实际上给你的感觉,你似乎想 - 只有构造函数使用泛型类型。

+0

有趣 - 感谢扩大我的理解了一下! – user3496060

相关问题