pet*_*ter -2 .net c# foreach multithreading .net-framework-version
我有一个foreach如下所示的循环
ArrayList list;
list = ftp.GetFileList(remotepath<ftp://ftp.getfilelist(remotepath/>);
foreach (string item in list)
{
}
Run Code Online (Sandbox Code Playgroud)
我Parallel.Foreach没有运气就转换成如下所示
ArrayList list;
list = ftp.GetFileList(remotepath<ftp://ftp.getfilelist(remotepath/>);
Parallel.ForEach(list.ToArra(), item =>
{
if (item.StartsWith("GExport_") &&(!item.ToUpper().Contains("DUM")))
{
}
}
Run Code Online (Sandbox Code Playgroud)
它抛出错误,如项目不包含StartsWith()扩展方法.怎么解决?
这是因为foreach在转换中的项目ArrayList,以string从object.a中的所有项ArrayList都object在编译时,并且object没有调用的方法StartsWith.
在这种情况下:
foreach (string item in list)
Run Code Online (Sandbox Code Playgroud)
item被转换为string从object.
要做同样的事情,你需要自己进行转换,例如
Parallel.ForEach(list.OfType<string>().ToArray(), item ....
Run Code Online (Sandbox Code Playgroud)
或者如果你想在运行时失败,.Cast<string>而不是OfType你的非字符串实例list.
或者使用通用列表,List<String>以避免运行时转换.