繁体   English   中英

C#,无法从“ System.Collections.Generic.IEnumerable”转换为“ string []”

[英]C#, cannot convert from 'System.Collections.Generic.IEnumerable' to 'string[]'

我有一些C#代码:

var oldLines = System.IO.File.ReadAllLines(path);
var newLines = oldLines.Where(line => !line.Contains(wordToDelete));
System.IO.File.WriteAllLines(path, newLines);

该代码可在新的Windows应用程序中使用。 但是,当我将该代码粘贴到现有应用程序中时,出现以下错误:

Error   2   Argument 2: cannot convert from
'System.Collections.Generic.IEnumerable<string>' to 'string[]'
Error   1   The best overloaded method match for
'System.IO.File.WriteAllLines(string, string[])' has some invalid
arguments

为什么会在新项目中引发此错误,而不是在我的旧项目中引发该错误?

oldLines.Where(line =>!line.Contains(wordToDelete)); 返回IEnumerable <字符串>

System.IO.File.WriteAllLines(path, newLines.ToArray());

会解决的

这可能是由另一个框架版本目标引起的。

newLinesIEnumerable<string>而不是string[] ,但是您的.NET版本(我认为是3.5)没有接受 .NET 4中引入IEnumerable<String>重载

因此,您只需要为File.WriteAllLines创建一个string[]或至少使用.NET 4:

System.IO.File.WriteAllLines(path, newLines.ToArray());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM