以下代碼給我一個InvalidCastException
,指出我無法在foreach
循環中從源類型轉換爲目標類型。我試過通過該方法傳遞多個不同的泛型集合,並且我總是得到這個錯誤。我無法弄清楚爲什麼。任何幫助,將不勝感激。實例化泛型時發生InvalidCastException
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'將創建該文件,如果它不存在,請刪除您的頂級檢查代碼。 –