You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET新手求助:无法将string[]隐式转换为System.Collections.ArrayList

解决"Cannot implicitly convert type 'string[]' to 'System.Collections.ArrayList'"错误

嗨,刚看了你的代码,这个错误原因很明确:sftp.GetFileList()方法返回的是string[]类型的数组,但你试图把它直接赋值给ArrayList类型的变量,这俩类型没法隐式转换,所以编译器报错了。

给你几个可行的解决方案,按推荐程度排序:

1. 直接使用string[](最推荐)

既然方法返回的就是字符串数组,直接用对应类型接收就行,类型更安全,代码也更简洁:

// 把ArrayList换成string[]
string[] filelist = sftp.GetFileList(pathGetFile);
bool is_twochar = false;
string temp = "";
foreach (var item in filelist)
{
    temp += item.ToString() + "\n"; // 注意这里是反斜杠的\n,不是/n
    if (item.ToString() == two_char)
    {
        is_twochar = true;
    }
}

2. 转换为ArrayList(仅兼容旧代码场景)

如果你因为某些历史原因必须用ArrayList,可以通过它的构造函数把数组转过去:

// 显式将数组转换为ArrayList
ArrayList filelist = new ArrayList(sftp.GetFileList(pathGetFile));

不过要提醒下,ArrayList是.NET早期的非泛型集合,没有类型检查,后续容易引发不必要的类型转换问题,现在更推荐用泛型集合替代它。

3. 改用List<string>(现代推荐方案)

如果需要更灵活的集合操作,也可以转成泛型的List<string>,类型安全还自带很多实用方法:

// 先引入using System.Linq;
List<string> filelist = sftp.GetFileList(pathGetFile).ToList();

另外,代码里的/n应该是\n(反斜杠),这个小细节也别忽略啦~

内容的提问来源于stack exchange,提问作者Lotte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:10:38