![](/img/trans.png)
[英]InvalidCastException: Activator.CreateInstance w/ Generic Inheriting Type
[英]InvalidCastException when instancing generic type
下面的代码给了我一个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());
}
}
}
您的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());
}
}
}
像这样使用var
:
foreach (var type in dataList)
{
sw.WriteLine(type.ToString());
}
您试图将列表中的每个项目键入为T
,但您的类型约束会强制T
为IEnumerable
。 我想你想将你的参数指定为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());
}
}
您应该尝试使用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());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.