以下代码为我提供了InvalidCastException
,声明我无法在foreach
循环中从源代码转换为目标类型。我尝试通过该方法传递多个不同的泛型集合,我总是得到这个错误。我无法弄清楚原因。任何帮助将不胜感激。
public static void WriteDataListToFile<T>(T dataList, string folderPath, string fileName) where T : IEnumerable, ICollection
{
//Check to see if file already exists
if(!File.Exists(folderPath + fileName))
{
//if not, create it
File.Create(folderPath + fileName);
}
using(StreamWriter sw = new StreamWriter(folderPath + fileName))
{
foreach(T type in dataList)
{
sw.WriteLine(type.ToString());
}
}
}
答案 0 :(得分:4)
您dataList
应为IEnumerable<T>
public static void WriteDataListToFile<T>(IEnumerable<T> dataList, string folderPath, string fileName)
{
//Check to see if file already exists
if (!File.Exists(folderPath + fileName))
{
//if not, create it
File.Create(folderPath + fileName);
}
using (StreamWriter sw = new StreamWriter(folderPath + fileName))
{
foreach (T type in dataList)
{
sw.WriteLine(type.ToString());
}
}
}
答案 1 :(得分:2)
像这样使用var
:
foreach (var type in dataList)
{
sw.WriteLine(type.ToString());
}
答案 2 :(得分:1)
您尝试将列表中的每个项目键入T
,但您的类型约束会强制T
为IEnumerable
。我想您要将参数指定为IEnumerable<T>
并删除类型约束:
public static void WriteDataListToFile<T>(IEnumerable<T> dataList, string folderPath, string fileName) //no type constraints
{
//your other things
foreach(T type in dataList)
{
sw.WriteLine(type.ToString());
}
}
答案 3 :(得分:0)
您应该尝试使用foreach
在Cast<T>
内投射您的收藏集。像这样:
public static void WriteDataListToFile<T>(T dataList, string folderPath, string fileName) where T : IEnumerable, ICollection
{
//Check to see if file already exists
if(!File.Exists(folderPath + fileName))
{
//if not, create it
File.Create(folderPath + fileName);
}
using(StreamWriter sw = new StreamWriter(folderPath + fileName))
{
// added Cast<T>
foreach(T type in dataList.Cast<T>())
{
sw.WriteLine(type.ToString());
}
}
}