2015-10-05 40 views
3

以下代碼給我一個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()); 
     } 
    } 
} 
+0

我很抑制你沒有得到一些其他異常。 'File.Create(folderPath + fileName);'是錯誤的,你打開一個'FileStream'並且從不關閉它。 'StreamWriter'將創建該文件,如果它不存在,請刪除您的頂級檢查代碼。 –

回答

2

使用var這樣的:

foreach (var type in dataList) 
{ 
    sw.WriteLine(type.ToString()); 
} 
+0

工作過。應該是真的很明顯。謝謝。 –

0

你應該嘗試使用Cast<T>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)) 
    { 
     // added Cast<T> 
     foreach(T type in dataList.Cast<T>()) 
     { 
      sw.WriteLine(type.ToString()); 
     } 
    } 
} 
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

您正在嘗試爲T列表內輸入的每個項目,但你的類型約束迫使TIEnumerable。我認爲,要指定您的參數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()); 
    } 
}