日期:2014-05-17  浏览次数:20841 次

泛型类型不定的情况下,怎么写?List<T> ,T不定
比如,有个DataTable,我想把List的类型赋成跟DataTable第1列一样的类型

DataTable dt...

Type T=dt.Columns[0].DataType;
List<T> lst = new List<T>();


这样写,语法是错误的,到底要怎么写呢?

------解决方案--------------------
直接用List<object>
------解决方案--------------------
public IList <T> GetList <T>(DataTable table)
{
IList <T> list = new List <T>();
T t = default(T);
PropertyInfo[] propertypes = null;
string tempName = string.Empty;
foreach (DataRow row in table.Rows)
{
t = Activator.CreateInstance <T>();
propertypes = t.GetType().GetProperties();
foreach (PropertyInfo pro in propertypes)
{
tempName = pro.Name;
if (table.Columns.Contains(tempName))
{
object value = row[tempName];
pro.SetValue(t, value, null);
}
}
list.Add(t);
}
return list;
}

tb.OfType<TableRow>().Select(row=>
new YourType{Field1=(string)row["field1"],Field2=(int)row["field2"]}).ToList();
------解决方案--------------------
搂主最终恐怕只能做类似的事情:

Type T=dt.Columns[0].DataType;

object lst = null;
if( T is TypeA ) lst = new List<TypeA>();
else if( T is TypeB ) lst = new List<TypeB>();
else if( T is TypeC ) lst = new List<TypeC>();
....

要么你得设计一个新类,让它拥有"变型"的类型,有点像Delphi那种Union类型的东西
,然后让这类通吃所有不同的 type 。


或许,你如果仅仅希望这个Union类能完成某项功能,那么建议你 将它换成一个专用接口 ,如:


DataTable dt...
List<IYourInterface> lst = new List<IYourInterface>();

IYourInterface mProduct = SomeFactory.Produce<IYourInterface>(dt.Columns[0]);
lst.Add( mProduct );
...




------解决方案--------------------
C# code

            Type type = dtable.Columns[0].DataType;//获取第0列的类型
            Type generic = typeof(List<>);//获取泛型集合类型
            generic = generic.MakeGenericType(new Type[] { type });//设置泛型对象
            var list = Activator.CreateInstance(generic) as IList;//创建泛型集合实例
            //如果列的类型为int,那么我们得到的list的类型为List<int>