gpt4 book ai didi

c# - 实例化泛型类型时出现 InvalidCastException

转载 作者:行者123 更新时间:2023-11-30 14:08:51 26 4
gpt4 key购买 nike

下面的代码给了我一个 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());
}
}
}

最佳答案

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

关于c# - 实例化泛型类型时出现 InvalidCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32957224/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com