以下代码给我一个 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());
}
}
}
File.Create(folderPath + fileName);
是错误的,你正在打开一个FileStream
但从未关闭它。如果文件不存在,StreamWriter
将创建该文件,请删除顶部的检查代码。 - Scott Chamberlain