实例化泛型类型时的 InvalidCastException 异常

3
以下代码给我一个 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
4个回答

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());
        }
    }
}

2

使用var来实现如下效果:

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

效果很好。其实应该很明显的。谢谢。 - Matthew Sawrey

1
您试图将列表中的每个项目类型定义为T,但是您的类型约束强制T成为IEnumerable
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());
    }
}

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());
         }
     }
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接