c# – 实例化泛型类型时出现InvalidCastException
发布时间:2020-12-15 23:28:07 所属栏目:百科 来源:网络整理
导读:下面的代码给了我一个InvalidCastException,声明我不能在foreach循环中从源类型转换为目标类型.我已经尝试通过该方法传递多个不同的泛型集合,我总是得到这个错误.我无法弄清楚为什么.任何帮助,将不胜感激. public static void WriteDataListToFileT(T dataLi
下面的代码给了我一个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()); } } } 解决方法
像这样使用
var :
foreach (var type in dataList) { sw.WriteLine(type.ToString()); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |