我有一个返回列表的通用方法'GetSomeData'。我可以是int,double,uint的列表...
public void GenericMethod<T>()
{
List<T> genericList = GetSomeData<T>();
List<double> castedList1 = (List<double>) genericList;
List<double> castedList2 = genericList.Cast<double>(); //Not working
List<double> castedList3 = genericList.Select(f => (double)f).ToList(); //not working
}
T可以是int,uint,double ......
有没有办法投这个名单?
答案 0 :(得分:0)
试试这个:
List<double> castedList3 = genericList.OfType<double>().ToList();
答案 1 :(得分:0)
这种方法很好,但如果T
无法转换为double
public void GenericMethod<T>() where T : struct
{
List<T> genericList = GetSomeData<T>();
IList<double> doubleList = genericList.Select(val => Convert.ToDouble(val))
.ToList();
}